mikedean (@mikedean)

Forum Replies Created

Viewing 1 replies (of 1 total)

  • mikedean
    Participant

    @mikedean

    A year later but here it is.

    This assumes a drop down select menu has been added to the form-topic.php template. wp_dropdown_categories() is used to make a <select> element for all the terms in the categories taxonomy so users can assign the topic to a term.
    https://codex.wordpress.org/Function_Reference/wp_dropdown_categories

    Then, the topic is assigned to the term they selected by hooking into the new topic process.

    /**
     * Assign a taxonomy term to a topic after it has been selected in the front end (using a <select> element).
     *
     * @param Int           $topic_id               The id for the current topic being created.
     * @param Int           $forum_id               The id for the current forum the topic is being created in.
     * @param Int           $anonymous_data         ??
     * @param Int           $topic_author           The id of the user who created the topic.
     *
     * @see https://codex.wordpress.org/Function_Reference/wp_dropdown_categories
     */
    
    //Update the taxonomy terms when a new topic is created or edited.
    add_action( 'bbp_new_topic', 'myprefix_assign_category_to_post', 20, 4 );
    
    function myprefix_assign_category_to_post( $topic_id, $forum_id, $anonymous_data, $topic_author ) {
            
            //Get the category submitted by the user
            $taxonomy_name = 'category';                    //the slug, or machine name, or the taxonomy
            $term_id = intval( $_POST['cat'] );             //Get value from the <select> element as an interger
    
            //@TODO error checking if term or taxonomy does not exists (returns false if so)
            $term_object = get_term_by( 'id', $term_id, $taxonomy_name );
    
            //Replace the existing subject with the selected one
            wp_set_post_terms( $topic_id, array( $term_id ), $taxonomy_name, false );
    }     
Viewing 1 replies (of 1 total)