modify all posts of a category to “no comments allowed”

I’m looking for a way to modify all posts of a certain category to be “no comments allowed” without going into each post settings, one by one, and modifying manually.

Perhaps a MySQL statement?

Read More

Thanks

Related posts

Leave a Reply

2 comments

  1. On your posts screen, you should be able to filter by category and then select all and bulk edit to turn off comments.

    Edit: Bulk actions only apply per page (e.g. 20 posts or however many you have showing), so you’ll either have to do it for each page of results or go up to screen options and increase the number of items that are showing on screen.

  2. To do it in WordPress directly you could use the following:

    <?php
        $args = array('category' => *term_id of category to disable comments for*);
        $myposts = get_posts($args);
        foreach($myposts as $post) {
             $my_post = array(
                 'ID' => $post->ID,
                 'comment_status' => 'closed'
             );
             wp_insert_post($my_post);     
        }        
    ?>
    

    get_posts() will retrieve all of the posts with the category specified in $args by:

    'category' => $term_id
    

    wp_insert_post() will allow you to modify said posts to disable comments with the following setting:

    'comment_status' => 'closed'
    

    You may wish to view the documentation pages for get_posts() and wp_insert_post() for more information.

    To ensure that no future posts under this category allow comments you could also use the save_post hook:

    save_post
    Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID.

    <?php
        add_action('save_posts', 'disable_comments');
        function disable_comments($post_id) {
            $disabled_category = /* term_id of the category to disable comments for */
            $category = get_the_category($post_id);
            if($category->cat_ID == $disabled_category) {
               $my_post = array(
                 'ID' => $post_id,
                 'comment_status' => 'closed'
               );
               wp_insert_post($my_post);     
            }
        }
    ?>
    

    get_the_category() will retrieve the category object for the selected post. Visiting the documentation is a good idea for more information on get_the_category().

    If you don’t know what an action hook is, you should visit this page.