Unmark a category x of all wordpress posts

Asked

Viewed 290 times

2

Is there a method to deselect a category "x" of all wordpress posts, without needing to enter one post at a time and deselect the category?

3 answers

3

Be able to uncheck all posts containing an "x" category using the following query:

DELETE FROM `wp_term_relationships` WHERE `term_taxonomy_id` = id_categoria

1

The logical thing is that this was done with the Bulk Edit Wordpress, as commented on answer from Ricardo. But I saw that the plugin Mass Set Categories consists of a single file; but the code seemed confusing and outdated, so I made a upgrade quick.

Basically, it’s an interface showing all posts and with checkboxes listing categories. The main functions are get_posts, get_categories and wp_set_post_categories.

I added an option in the first post which copies the value of checkbox for everyone else posts to mark/unmark in bulk.

plugin screenshot

<?php
/**
 * Plugin Name: (SOPT) Mass Set Categories
 * Plugin URI:  /a/9006/201
 * Description: Baseado em http://wordpress.org/plugins/mass-set-post-categories/. Código revisado, simplificado e com nova funcionalidade de "Marcar/desmarcar todos".
 * Author:      brasofilo
 * License:     GPLv3
 */

add_action(
    'plugins_loaded',
    array ( B5F_Mass_Set_Categories::get_instance(), 'plugin_setup' )
);

class B5F_Mass_Set_Categories
{
    protected static $instance = NULL;
    public $plugin_url = '';
    public $plugin_path = '';

    /**
     * Acessar a instancia de trabalho deste plugin.
     *
     * @wp-hook plugins_loaded
     * @return  object of this class
     */
    public static function get_instance()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    /**
     * Usado para iniciar os trabalhos normais do plugin.
     *
     * @wp-hook plugins_loaded
     * @return  void
     */
    public function plugin_setup()
    {
        $this->plugin_url    = plugins_url( '/', __FILE__ );
        $this->plugin_path   = plugin_dir_path( __FILE__ );
        add_action( 'admin_menu', array( $this, 'set_plugin_page' ) );
    }

    /**
     * Constructor. Deixado publico e vazio intencionalmente.
     *
     * @see plugin_setup()
     */
    public function __construct() {}

    /**
     * Definir a página do plugin
     *
     * @wp-hook admin_menu
     */
    public function set_plugin_page () 
    {
        $hook = add_posts_page(
            'Mass Categories' ,  
            'Mass Categories',   
            'manage_options',  
            'mass-set-cats-t2',  
            array( $this, 'display_plugin_page' )
        );
        add_action( "admin_footer-$hook", array( $this, 'javascript' ) );
    }

    /**
     * Mostrar a página HTML do plugin
     * 
     * @return void
     */
    public function display_plugin_page() 
    {
        $args = array(
            'numberposts'     => -1,
            'offset'          => 0,
            'orderby'         => 'post_date',
            'order'           => 'DESC',
            'post_type'       => 'post',
            'post_status'     => 'publish' 
        ); 
        $posts = get_posts( $args );
        $boxes = $this->get_all_categories();
        ?> 
        <div class="wrap">
        <h2>Mass Set Categories</h2>
        Total posts: <?php echo count( $posts ); ?>
        </div>
        <?php $this->check_posted_data(); // imprime a mensagem de update abaixo do título ?>
        <div style="background-color:#FFF; border:#ccc 2px solid; padding:10px; width:95%"> 
        <form action="" enctype="multipart/form-data" method="post" >
         <input type="submit"  name="setcats" value="Submit" class="button-primary" >   <br />
        <?php
            wp_nonce_field( plugin_basename( __FILE__ ), 'mass-set-cats-t2' );
            $print_str = '';
            $select_all = true;
            foreach ( $posts as $p )
            {
                $cats = get_the_category( $p->ID );
                $print_str .= '<h3><a href="' . get_edit_post_link($p->ID) . '">' . $p->post_title . "</a></h3>";
                foreach( $boxes as $id => $name )
                {
                    $check = $b1 = $b2 = $select_box = ''; // Reset aux vars
                    $filler = str_repeat( ' -', 30 - strlen(utf8_decode($id)) - strlen(utf8_decode($name)) ); // Recheio, considera caracteres acentuados
                    if( $select_all )
                    {
                        $select_box = sprintf(
                            '%1$s <a href="#" data-cat="[%2$s]" data-id="data-%3$s-%2$s" class="select-all">%4$s</a>',
                            $filler,
                            $id,
                            $p->ID,
                            __('Copy to all')
                        );
                    }
                    foreach( $cats as $c )
                    {
                        if( $c->term_id == $id )
                        {
                            $check = 'checked="checked"';
                            $b1 = '<b>';
                            $b2 = '</b>';
                        } 
                    }
                    $print_str .= sprintf( 
                        '<label><input type="checkbox" id="data-%1$s-%2$s" name="data[%1$s][%2$s]" %3$s>%4$s: %5$s</label>%6$s<br />',
                        $p->ID,
                        $id,
                        $check,
                        $b1 . $id,
                        $name . $b2,
                        $select_box
                    );
                }
                if( $select_all )
                    $select_all = false;
                $print_str .= '<hr />';
            }
            $print_str .= '</div>';
            echo $print_str; 
            ?>
         <input type="submit"  name="setcats" value="Submit" class="button-primary" >   
         </form>   
        <?php 
    }

    /**
     * Conferir nossos dados na global $_POST, usa nonce por segurança
     * 
     * @return void
     */
    private function check_posted_data()
    {
        if( !isset( $_POST['mass-set-cats-t2'] ) || !wp_verify_nonce( $_POST['mass-set-cats-t2'], plugin_basename( __FILE__ ) ) )
            return;

        if( isset( $_POST['setcats'] ) && $_POST['setcats'] == true )
        {
            foreach ( $_POST['data'] as $object_id => $cats )
            {
                 $ids = array_keys( $cats );
                 $ids = array_map( 'intval', $ids );
                 $ids = array_unique( $ids );
                 wp_set_post_categories( $object_id, $ids );
                 $ids = implode( ', ',$ids );
            }
            echo '<div style="width:99%; padding: 5px;" class="updated below-h2"><p>Updated</p></div>';
        }
    }

    /**
     * Recuperar todas as categorias e devolver IDs e Names
     *
     * @return array
     */
    private function get_all_categories()
    {
        $args = array(
            'type'                     => 'post',
            'child_of'                 => 0,
            'parent'                   => '',
            'orderby'                  => 'id',
            'order'                    => 'ASC',
            'hide_empty'               => 0,
            'hierarchical'             => 1,
            'exclude'                  => '',
            'include'                  => '',
            'number'                   => '',
            'taxonomy'                 => 'category',
            'pad_counts'               => false );
        $categories = get_categories( $args ); 
        $boxes = array();
        foreach( $categories as $c )
        {
            $boxes[$c->term_id] = $c->name;
        }
        return $boxes;
    }

    /**
     * Imprimir JavaScript no footer da página do plugin
     *
     * @wp-hook admin_footer-$plugin_page
     * @return void
     */
    public function javascript()
    {
        ?>
        <script type="text/javascript"> 
            jQuery(document).ready(function($) 
            { 
                // Classe comum a todos os checkboxes
                $('.select-all').click( function()
                { 
                    // A category-id do elemento clicado
                    var data_cat = '[' + $(this).data('cat') + ']'; 
                    // Cada categoria comparte o mesmo data-id
                    var data_id = '#' + $(this).data('id'); 
                    $("input[name$='"+data_cat+"']").each( function() 
                    {
                        // Marcar todas as categorias igual que a clicada
                        $(this).prop( 'checked', $(data_id).prop('checked') ); 
                    });
                });
            });             
        </script>
        <?php
    }
}

1

Mass set Categories

Has this plugin that adds and removes categories in bulk.

It presents all posts at once, you will mark and uncheck the ones you want.


There is also a idea for something similar to be implemented in Wordpress.

  • this plugin lists all posts, I want something that unchecks all posts automatically that contains category "sustainability".

  • It’s not easier to delete the category then?

  • No, because it serves to organize the subcategories, but registered wrong, only if you mark the daughter category, because it works with hierarchy, I managed using sql query, I will post as answer if someone needs too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.