Skip to content

Instantly share code, notes, and snippets.

@apos37
Created April 22, 2025 18:12
Show Gist options
  • Save apos37/68e27ab6aa12488b4f50e6996fbcd783 to your computer and use it in GitHub Desktop.
Save apos37/68e27ab6aa12488b4f50e6996fbcd783 to your computer and use it in GitHub Desktop.
Creating a new forum programmatically and sorting them alphabetically
<?php
class myForumClass {
/**
* Add a new forum topic
*
* @param string $name
* @param string $slug
* @param string $description
* @param string $icon
* @param integer $cat_id
* @param integer $parent_id
* @param integer $sort
* @param string $forum_status
* @return mixed
*/
public function add_forum( $name, $slug = '', $description = '', $icon = 'fas fa-plug', $cat_id = 45, $parent_id = 0, $sort = 1, $forum_status = 'normal' ) {
global $wpdb;
// Check if the forum already exists by slug or name
$existing_forum = $wpdb->get_var( $wpdb->prepare(
"SELECT id FROM {$wpdb->prefix}{$this->forums_table} WHERE slug = %s OR name = %s LIMIT 1",
$slug,
$name
) );
if ( $existing_forum ) {
return $existing_forum;
}
// Prepare the data for the insert
$data = [
'name' => sanitize_text_field( $name ),
'parent_id' => absint( $cat_id ),
'parent_forum' => absint( $parent_id ),
'description' => sanitize_textarea_field( $description ),
'icon' => sanitize_text_field( $icon ),
'sort' => absint( $sort ),
'forum_status' => sanitize_key( $forum_status ),
'slug' => sanitize_title( $slug )
];
// Insert into the database
$inserted = $wpdb->insert(
$wpdb->prefix . $this->forums_table,
$data
);
// Check if insert was successful
if ( false === $inserted ) {
error_log( 'Failed to create forum for ' . $name );
return new \WP_Error( 'insert_failed', 'Failed to insert the forum.' );
}
// Insert the new forum
$new_forum_id = $wpdb->insert_id;
// Reorder everything alphabetically now that the new forum exists
$this->reorder_forums_alphabetically( $parent_id, $cat_id );
return $new_forum_id;
} // End add_forum()
/**
* Reorder the forums alphabetically
*
* @param integer $parent_id
* @param integer $cat_id
* @return void
*/
public function reorder_forums_alphabetically( $parent_id = 0, $cat_id = 45 ) {
global $wpdb;
$table = $wpdb->prefix . 'forum_forums';
// Get all forums in this category and parent, ordered by name
$forums = $wpdb->get_results( $wpdb->prepare(
"SELECT id, name FROM {$table} WHERE parent_id = %d AND parent_forum = %d ORDER BY name ASC",
$cat_id,
$parent_id
) );
// Assign new sort values
$sort_order = 1;
foreach ( $forums as $forum ) {
$wpdb->update(
$table,
[ 'sort' => $sort_order ],
[ 'id' => $forum->id ],
[ '%d' ],
[ '%d' ]
);
$sort_order++;
}
} // End reorder_forums_alphabetically()
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment