Skip to:
Content
Pages
Categories
Search
Top
Bottom

Topics Created via API Aren’t Showing


  • rilliencot
    Participant

    @rilliencot

    WordPress Version: 6.4.2
    bbPress Version: 2.6.9
    Link to site: Unavailable (Site created using LocalWP and still hosted locally)

    When I create topics through the standard frontend or backend, the new topic shows up in the forum perfectly.

    However, if I create a new topic using a plugin extension I’ve cobbled together, the new topic does not show up on the front end of the website (despite it being created and visible on the back end).

    The plugin written in php is as follows (thanks to work from here and here):

    
    <?php
    /**
     * Plugin Name:       bbPress API
     * Description:       Exposing the bbPress post types to WP API.
     * Author:            Rillien Cot
     * Version:           1.3.0
     */
    
    /**
     * Add REST API support to an already registered post type.
     */
    add_action('init', 'register_bbp_post_types', 25);
    
    function register_bbp_post_types() {
        global $wp_post_types;
    
        $post_type_name =  bbp_get_reply_post_type();
        if (isset($wp_post_types[$post_type_name])) {
            $wp_post_types[$post_type_name]->show_in_rest = true;
            $wp_post_types[$post_type_name]->rest_base = $post_type_name;
            $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
        }
        $post_type_name =  bbp_get_topic_post_type();
        if (isset($wp_post_types[$post_type_name])) {
            $wp_post_types[$post_type_name]->show_in_rest = true;
            $wp_post_types[$post_type_name]->rest_base = $post_type_name;
            $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
        }
        $post_type_name =  bbp_get_forum_post_type();
        if (isset($wp_post_types[$post_type_name])) {
            $wp_post_types[$post_type_name]->show_in_rest = true;
            $wp_post_types[$post_type_name]->rest_base = $post_type_name;
            $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
        }
    
        // Add custom REST API endpoint for creating bbPress topic
        add_action('rest_api_init', 'create_bill_endpoint');
    }
    
    function create_bill_endpoint() {
        register_rest_route('pnyx/v2', '/bill/', array(
            'methods' => 'POST',
            'callback' => 'create_bill',
        ));
    }
    
    function create_bill($data) {
        // Extract necessary data from the request
        $forum_id = $data['forum_id'];
        $topic_title = $data['topic_title'];
        $topic_content = $data['topic_content'];
        $bill_id = $data['bill_id'];
    
        // Create a new bbPress topic
        $topic_args = array(
            'post_title' => $topic_title,
            'post_content' => $topic_content,
            'post_type' => bbp_get_topic_post_type(),
            'post_status' => 'publish',
            'post_parent' => $forum_id, // Set the post_parent to the forum ID
        );
    
        $topic_id = wp_insert_post($topic_args);
    ?>
    

    Basically, it exposes the Forum, Topic, and Reply post types from bbPress to standard wp-json/v2 namespace and then adds an additional endpoint (‘create_bill’) which allows me to add a new topic and associate it with a forum via ‘post_parent’. (I wonder if this is where the problem is?)

    I create a new topic using the following python script:

    
    import requests
    import json
    
    # Set WordPress API authentication details
    username = "*******"
    password = "**********************"
    auth = requests.auth.HTTPBasicAuth(username, password)
    
    # Values for new post data
    new_post_data = {
        "forum_id": 40, # <- This is a valid post id of a forum.
        "topic_title": "New API Topic Title",
        "topic_content": "Lorem ipsum content for the new topic"
    }
    
    # Make the POST request to create a new post
    wordpress_api_url = "http://pnyx.local/wp-json/pnyx/v2/bill/"
    response = requests.post(
        wordpress_api_url,
        auth=auth,
        headers={
            'Content-Type': 'application/json',
        },
        data=json.dumps(new_post_data)
    )
    

    The topic is created, and I can see it in Dashboard>>Topics>>All Topics. And I can view it by going directly to the link associated with it, but I can’t see it on the actual frontend of the forum.

    I’ve deactived all other plugins and I’m still getting this issue. The only differences between the two (as far as I can tell) are the Author IP (API created topics leave this field blank, standard fills it with 127.0.0.1) and the number of voices (API created topics have 0, standard created topics have 1). All the other settings seem identical (visibilty = public, type = normal, status = open).

    Any insights as to what I’m missing and how to rectify the situation are greatly appreciated, thanks!

Viewing 8 replies - 1 through 8 (of 8 total)

  • rilliencot
    Participant

    @rilliencot

    I’m also discovering that the when I create a new topic via the standard route, the following post meta fields are generated in the wp_postMeta table for the topic:

    edit_lock
    edit_last
    bbp_forum_id
    bbp_author_ip
    bbp_last_reply_id
    bbp_last_active_id
    bbp_last_active_time
    bbp_reply_count
    bbp_reply_count_hidden
    bbp_voice_count

    However, these do not get generated when I create a topic through my API. I have a feeling this is the issue. I’m not really sure what I’m supposed to do about this though. I notice the bbp_forum_id field is included in there. Should I be using this to set that field instead of shoehorning through ‘post_parent’ in an additional plugin?


    rilliencot
    Participant

    @rilliencot

    Figured it out.

    It was an issue with the post meta content. For topics to appear in forums, they apparently need to have a ‘_bbp_last_active_time’. I was able to add this by adding the line add_post_meta($topic_id, '_bbp_last_active_time', date('Y-m-d H:i:s')); right below the $topic_id = wp_insert_post($topic_args); line in the php file (with the date function getting the current datetime and returning it in the proper format).


    Robin W
    Moderator

    @robin-w

    for completeness look at

    \bbpress\includes\topics\functions.php line 96

    This is what bbpress does to create a new topic.

    on line 378 it has a hook

    do_action( 'bbp_new_topic',......

    which is used in

    bbpress\bbpress\includes\core\actions.php

    Line 206: add_action( 'bbp_new_topic',  'bbp_update_topic', 10, 5 );
    Line 241: add_action( 'bbp_new_topic',    'bbp_notify_forum_subscribers', 11, 4 );
    Line 287: add_action( 'bbp_new_topic',        'bbp_increase_forum_topic_count' );
    Line 327: add_action( 'bbp_new_topic',     'bbp_increase_user_topic_count' );
    Line 346: add_action( 'bbp_new_topic', 'bbp_update_topic_engagements', 20 );
    Line 350: add_action( 'bbp_new_topic', 'bbp_update_topic_voice_count', 30 );

    to call the other functions that update the meta, and thus get the topic to show.


    Robin W
    Moderator

    @robin-w

    when you have completed, in the spirit of open software and helping others, can you post your final solution code please


    rilliencot
    Participant

    @rilliencot

    Although I solved the last issue, a similar one immediately came up after that (The topic count at the top of a forum didn’t count new topics). I had a feeling that as long as I proceeded with this hacked version of the actual bbPress functions that I now thankfully know are responsible for topic creation (thank you Robin, again!), these little discrepencies were going to keep popping up.

    So I’ve updated the ‘create_bill’ function to now call bbp_insert_topic() (line 24 of \bbpress\includes\topics\functions.php). If I understand things correctly (I’m new to web development and learning as I go), this starts the natural chain of events that should happen anytime a new topic is created (at least it looks to be working). I still need the new endpoint because I’d like to add some custom fields to these topics as well, so now the above php script is the much simpler:

    <?php
    /**
     * Plugin Name:       bbPress Bill API
     * Description:       Exposing the bbPress post types to WP API and creating a namespace for bills.
     * Author:            Rillien Cot
     * Version:           1.6.0
     */
    
    /**
     * Add REST API support to an already registered post type.
     */
    add_action('init', 'register_bbp_post_types', 25);
    
    function register_bbp_post_types() {
        global $wp_post_types;
    
        $post_type_name =  bbp_get_reply_post_type();
        if (isset($wp_post_types[$post_type_name])) {
            $wp_post_types[$post_type_name]->show_in_rest = true;
            $wp_post_types[$post_type_name]->rest_base = $post_type_name;
            $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
        }
        $post_type_name =  bbp_get_topic_post_type();
        if (isset($wp_post_types[$post_type_name])) {
            $wp_post_types[$post_type_name]->show_in_rest = true;
            $wp_post_types[$post_type_name]->rest_base = $post_type_name;
            $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
        }
        $post_type_name =  bbp_get_forum_post_type();
        if (isset($wp_post_types[$post_type_name])) {
            $wp_post_types[$post_type_name]->show_in_rest = true;
            $wp_post_types[$post_type_name]->rest_base = $post_type_name;
            $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
        }
    
        // Add custom REST API endpoint for creating bbPress topic
        add_action('rest_api_init', 'create_bill_endpoint');
    }
    
    function create_bill_endpoint() {
        register_rest_route('pnyx/v2', '/bill/', array(
            'methods' => 'POST',
            'callback' => 'create_bill',
        ));
    }
    
    function create_bill($data) {
        // Extract Data
        $new_topic_data = $data['new_post_data'];
        $new_topic_meta = $data['new_post_meta'];
    
        // Create new bbPress topic using passed data and meta content
        $topic_id = bbp_insert_topic($new_topic_data, $new_topic_meta);
    
        // Add ACF custom fields to created topic
        update_field('bill_id', $data['bill_id'], $topic_id);
    }
    ?>

    and the python that calls it is:

    import requests
    import json
    
    # Set your WordPress API authentication details
    username = "************"
    password = "***********************"
    auth = requests.auth.HTTPBasicAuth(username, password)
    
    # Create a new post data with post_parent
    new_post_payload = {
        "new_post_data": {
            "post_parent": 40, // use a valid forum_id from your site
            "post_title": "API Created Post Title",
            "post_content": "Lorem ipsum content for the new topic",
        },
        "new_post_meta": {
            "forum_id": 40, //use same forum_id here that you used for "post parent" in 'new_post_data'
        },
        "bill_id": "hrs1111",
    }
    
    # Make the POST request to create a new post
    wordpress_api_url = "http://pnyx.local/wp-json/pnyx/v2/bill/"
    response = requests.post(
        wordpress_api_url,
        auth=auth,
        headers={
            'Content-Type': 'application/json',
        },
        data=json.dumps(new_post_payload),
    )

    You’ll notice that the ‘data’ portion of the request has changed from a simple dictionary to nested dictionaries so the bbp_insert_topic function has the correct arguments (it takes two arrays).


    Robin W
    Moderator

    @robin-w

    great and thanks for posting back the solution – so are you all fixed ?


    rilliencot
    Participant

    @rilliencot

    Yep! Switching to the bbp_insert_topic function solved the issues I was having with various things not working correctly.

    Thanks again for pointing out where all of that stuff was. I could tell my version was bad but it was the best I had been able to cobble together with my limited understanding. I was in one of those “too ignorant to even know what to look for” phases. I had a (genuinely) fun 4 hours this morning putting together how all of these plugins actually work. It would’ve been longer and frustrating trying to understand why my version wasn’t fully working without the guidance.


    Robin W
    Moderator

    @robin-w

    great – glad you are fixed 🙂

Viewing 8 replies - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.
Skip to toolbar