Support » Developing with WordPress » Change post category when a comment is posted

  • Howdy!

    I modified my WordPress comment section to show only a button (Book!) that posts a prewritten comment (I’m booking this):

    <?php if (in_category( 'available' )) : ?>
    	<?php if ( comments_open() ) { comment_form(array(
    		'title_reply'=>'',
    		'label_submit' => esc_html__( 'Book!' ),
    		'comment_field' => '<textarea id="comment" name="comment" cols="45" rows="5" maxlength="65525" required="" style="display:none">'. __('I'm booking this.','textdomain').'</textarea>',
    		)); } ?>
    <?php endif;?>

    Now: when the first comment has ben posted I would like the category of the post to change from ‘available’ to ‘booked’… I’m guessing I should use something like this:

    wp_set_object_terms( $post_id, $category, 'booked' );

    But where and how do I put that piece of code into action…? 🤔

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    You can use the ‘wp_insert_comment’ action hook to do other things anytime a comment is inserted into the DB. Besides setting a post term, you may want to verify the comment is approved and that it’s related to an object where booking makes sense.
    https://developer.wordpress.org/reference/hooks/wp_insert_comment/

    Thread Starter joxyzan

    (@joxyzhan)

    Sounds good @bcworkz ! The bad thing is I can’t write that code. (I’m in the very start of learning php…) Could you help me? 😬

    Would the hook be placed as an action in the functions.php? And is it possible to make it fire only when the first comment is made on a post in a certain category?

    The site I’m working on is available to logged in members of my association only, so all comments are automatically approved and considered valid for booking.

    Moderator bcworkz

    (@bcworkz)

    functions.php is one option. Or you could create a simple plugin which contains the code. It’s easier than it sounds. If your theme is subject to periodic updates, functions.php is not a good choice unless it’s for a child theme you create. Plugins are simpler to create than child themes.

    An action hook fires every time the related function is called. This can be multiple times per request. It’s up to your callback function to decide if something should be done or not.

    I’m unable to provide full working code, but I can offer a basic structure where you’d need to add to to do what the comments suggest.

    add_action('wp_insert_comment','jz_handle_booking', 10, 2 );
    function jz_handle_booking($id, $comment_obj) {
      $post_ID = $comment_obj->comment_post_ID;
      //verify $post_ID relates to a bookable post type
      //if a bookable post type:
        $count = get_comments([
          'count'=> true,
          'post_id'=> $post_ID,
          'comment__not_in'=> [$id,],
        ]);
        if ( 0 == $count ) {
          wp_set_object_terms( $post_ID, 'booked', 'category');
        }
      //endif;
    }

    Alternative to checking comment count is checking if $post_ID is already assigned “booked” category term.

    I hope that’s enough to get you started in the right direction.

    Thread Starter joxyzan

    (@joxyzhan)

    Hello @bcworkz !

    I’m getting back to you hoping for another answer on this weird little subject. 😅

    I rewrote the code for posting a prewritten comment and successfully added the change of category in this way:

    <?php if(isset($_POST['book'])){ 
    $data = array(
    	'comment_content' => 'I´m booking this.',
    	'comment_post_ID' => $post_id,
    	'comment_author' => $current_user->display_name,
    	'comment_author_email' => $current_user->user_email,
    	'comment_author_url' => $current_user->user_url, 
    	);
    wp_new_comment($data);
    wp_set_object_terms( $post_id, null, 'category' ); 
    wp_set_object_terms( $post_id, 'booked', 'category' );
    echo "<meta http-equiv='refresh' content='0'>";
    } ?>
    
    <form method="post" action="">
    <input name="book" type="submit" id="submit" class="submit" value="Book!">
    </form>

    It works great! 🥳

    Except that an error flashes before refreshing the page the way I do (with the echo statement):
    “Warning: Cannot modify header information – headers already sent by…”

    Any ideas on how to refresh the page without getting the error?

    • This reply was modified 4 months, 1 week ago by joxyzan.
    Thread Starter joxyzan

    (@joxyzhan)

    PS. I’m a little confused about why I have to include parameters 2-5 in the $data-array so any clarification/simplification on that would also be very much appreciated. 🙂

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