| 1 |
<?php |
| 2 |
/** |
| 3 |
* Create Topic functionality |
| 4 |
* |
| 5 |
* @package Forumax |
| 6 |
*/ |
| 7 |
|
| 8 |
defined( 'ABSPATH' ) || exit; |
| 9 |
|
| 10 |
// AJAX handler to create a topic |
| 11 |
add_action( 'wp_ajax_forumax_create_topic', 'forumax_create_topic' ); |
| 12 |
|
| 13 |
/** |
| 14 |
* Create a new topic. |
| 15 |
*/ |
| 16 |
function forumax_create_topic() { |
| 17 |
|
| 18 |
// Check the nonce |
| 19 |
check_ajax_referer( 'bbpc-admin-nonce', 'bbpc_nonce' ); |
| 20 |
|
| 21 |
if ( ! current_user_can( 'manage_options' ) ) { |
| 22 |
wp_send_json_error( 'Unauthorized request.' ); |
| 23 |
} |
| 24 |
|
| 25 |
$bbp_topic_title = isset( $_POST['bbp_topic_title'] ) ? sanitize_text_field( wp_unslash( $_POST['bbp_topic_title'] ) ) : ''; |
| 26 |
if ( empty( $bbp_topic_title ) ) { |
| 27 |
wp_send_json_error( 'Topic title cannot be empty.' ); |
| 28 |
} |
| 29 |
|
| 30 |
$forum_id = ! empty( $_POST['forum_id'] ) ? absint( $_POST['forum_id'] ) : 0; |
| 31 |
$topic_author = bbp_get_current_user_id(); |
| 32 |
|
| 33 |
if ( ! bbp_is_forum( $forum_id ) ) { |
| 34 |
wp_send_json_error( 'Invalid forum.' ); |
| 35 |
} |
| 36 |
|
| 37 |
// Only the count is needed. |
| 38 |
$parent_items = new WP_Query( [ |
| 39 |
'post_parent' => $forum_id, |
| 40 |
'post_type' => 'topic', |
| 41 |
'post_status' => 'any', |
| 42 |
'posts_per_page' => 1, |
| 43 |
'fields' => 'ids', |
| 44 |
'update_post_meta_cache' => false, |
| 45 |
'update_post_term_cache' => false, |
| 46 |
] ); |
| 47 |
|
| 48 |
$add = 2; |
| 49 |
$order = (int) $parent_items->found_posts + $add; |
| 50 |
|
| 51 |
// Create topic object |
| 52 |
$topic_data = apply_filters( 'bbp_new_topic_pre_insert', [ |
| 53 |
'post_author' => $topic_author, |
| 54 |
'post_title' => $bbp_topic_title, |
| 55 |
'post_parent' => $forum_id, |
| 56 |
'post_content' => '', |
| 57 |
'post_type' => bbp_get_topic_post_type(), |
| 58 |
'post_status' => 'publish', |
| 59 |
'menu_order' => $order, |
| 60 |
] ); |
| 61 |
|
| 62 |
$topic_id = wp_insert_post( $topic_data, true ); |
| 63 |
|
| 64 |
if ( is_wp_error( $topic_id ) ) { |
| 65 |
wp_send_json_error( 'Failed to create the topic.' ); |
| 66 |
} |
| 67 |
|
| 68 |
do_action( 'bbp_new_topic', $topic_id, $forum_id, '', $topic_author ); |
| 69 |
wp_send_json_success( 'Topic created successfully.' ); |
| 70 |
} |
| 71 |
|