Taxonomy list. Order by a specific custom post type count

admin2025-04-18  0

I have a custom taxonomy and two custom post types (A and B post types).
I created a taxonomy list and this list also display B posts type count of taxonomy. Taxonomy list is ordered by post count.

My problem is that the ordering of taxonomy is going according to the total post count ( total count of both A and B post types ).
I want ordering also to be according to B post type count of taxonomy.
Code based on WP Categories Widget
Please, need help this with my code:

<?php
/*
Plugin Name: WP Categories Widget
Plugin URI: /
Description: It's a very simple plugin to display categories list in your website sidebar and you can define category list for your own custom taxonomy.
Author: MR Web Solution
Author URI: 
Version: 1.4
*


/*  Copyright 2018-19  wp-categories-widget  (email : [email protected])

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**************************************************************
                START CLASSS WpCategoriesWidget 
**************************************************************/
class WpCategoriesWidget extends WP_Widget {

    /**
     * Register widget with WordPress.
     */
    function __construct() {
        parent::__construct(
            'wp_categories_widget', // Base ID
            __( 'WP Categories list', 'mrwebsolution' ), // Name
            array( 'description' => esc_html__( 'Display categories list of all taxonomy post type', 'mrwebsolution' ), ) // Args
        );
        if(!is_admin())
        add_action('wcw_style',array($this,'wcw_style_func'));
        add_filter( "plugin_action_links_".plugin_basename( __FILE__ ), array(&$this,'wcw_add_settings_link') );
    }

    /**
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        echo $args['before_widget'];
        if ( ! empty( $instance['wcw_title'] ) && !$instance['wcw_hide_title']) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['wcw_title'] ) . $args['after_title'];
        }
        // add css      
        do_action('wcw_style','wcw_style_func');
        /** return category list */
        if($instance['wcw_taxonomy_type']){
            $va_category_HTML ='<div class="ve-cat-widget-div">';
            $va_category_HTML .='<ul class="ve-cat-widget-listing">';
                $args_val = array( 'hide_empty=0' );    
                $i=1;
                $excludeCat= $instance['wcw_selected_categories'] ? $instance['wcw_selected_categories'] : '';
                $wcw_action_on_cat= $instance['wcw_action_on_cat'] ? $instance['wcw_action_on_cat'] : '';
                if($excludeCat && $wcw_action_on_cat!='')
                $args_val[$wcw_action_on_cat] = $excludeCat;
                function wpse340250_term_count( WP_Term $term, $post_type) {
    $q_args = [
        'post_type' => $post_type,
        'nopaging' => true, // no limit, pagination
        'fields' => 'ids', // only return post id's instead of full WP_Post objects will speed up
        'tax_query' => array(
            array(
                'taxonomy' => $term->taxonomy,
                'field'    => 'term_id',
                'terms'    => $term->term_id,
            ),
        ),
    ];
    $term_count = get_posts($q_args);

    return count($term_count);
}

                $terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' => 'count', 'order' => 'DESC','hide_empty'=>0 ));
                if ( $terms ) { 
                    foreach ( $terms as $term ) {
                        $term_link = get_term_link( $term );
                        if ( is_wp_error( $term_link ) ) {
                        continue;
                        }

                    $carrentActiveClass=''; 

                    if($term->taxonomy=='category' && is_category())
                    {
                      $thisCat = get_category(get_query_var('cat'),false);
                      if($thisCat->term_id == $term->term_id)
                        $carrentActiveClass='class="active-cat"';
                    }

                    if(is_tax())
                    {
                        $currentTermType = get_query_var( 'taxonomy' );
                        $cat_icon = get_field('logo', $queried_object);
                        $termId= get_queried_object()->term_id;
                         if(is_tax($currentTermType) && $termId==$term->term_id)
                          $carrentActiveClass='class="active-cat"';


                    }   
                        $icon = get_field('logo', $term->taxonomy . '_' . $term->term_id); 
                        $va_category_HTML .= '<li class="logolar" '.$carrentActiveClass.'>' .'<a class="rownum">' .$i++. '</a>'. '</a>';
                        $va_category_HTML .= sprintf('<img src="%s" />', $icon) . '</a>';
                        $va_category_HTML .='<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>';
                        if (empty( $instance['wcw_hide_count'] )) {
                        $va_category_HTML .='<span class="post-count">'.wpse340250_term_count($term, 'sikayet').(' şikayət').'</span>';
                        }

                        $va_category_HTML .='</li>';
                    }
                }
            $va_category_HTML .='</ul></div>';
            echo $va_category_HTML;
            }   
        echo $args['after_widget'];
    }

    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $wcw_title                  = ! empty( $instance['wcw_title'] ) ? $instance['wcw_title'] : esc_html__( 'WP Categories', 'virtualemployee' );
        $wcw_hide_title             = ! empty( $instance['wcw_hide_title'] ) ? $instance['wcw_hide_title'] : esc_html__( '', 'virtualemployee' );
        $wcw_taxonomy_type          = ! empty( $instance['wcw_taxonomy_type'] ) ? $instance['wcw_taxonomy_type'] : esc_html__( 'category', 'virtualemployee' );
        $wcw_selected_categories    = (! empty( $instance['wcw_selected_categories'] ) && ! empty( $instance['wcw_action_on_cat'] ) ) ? $instance['wcw_selected_categories'] : esc_html__( '', 'virtualemployee' );
        $wcw_action_on_cat          = ! empty( $instance['wcw_action_on_cat'] ) ? $instance['wcw_action_on_cat'] : esc_html__( '', 'virtualemployee' );
        $wcw_hide_count             = ! empty( $instance['wcw_hide_count'] ) ? $instance['wcw_hide_count'] : esc_html__( '', 'virtualemployee' );
        ?>
        <p>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label> 
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_title' ) ); ?>" type="text" value="<?php echo esc_attr( $wcw_title ); ?>">
        </p>
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_hide_title' ) ); ?>" type="checkbox" value="1" <?php checked( $wcw_hide_title, 1 ); ?>>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_title' ) ); ?>"><?php _e( esc_attr( 'Hide Title' ) ); ?> </label> 
        </p>
        <p>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_taxonomy_type' ) ); ?>"><?php _e( esc_attr( 'Taxonomy Type:' ) ); ?></label> 
        <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_taxonomy_type' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_taxonomy_type' ) ); ?>">
                    <?php 
                    $args = array(
                      'public'   => true,
                      '_builtin' => false

                    ); 
                    $output = 'names'; // or objects
                    $operator = 'and'; // 'and' or 'or'
                    $taxonomies = get_taxonomies( $args, $output, $operator ); 
                    array_push($taxonomies,'category');
                    if ( $taxonomies ) {
                    foreach ( $taxonomies as $taxonomy ) {

                        echo '<option value="'.$taxonomy.'" '.selected($taxonomy,$wcw_taxonomy_type).'>'.$taxonomy.'</option>';
                    }
                    }

                ?>    
        </select>
        </p>
        <p>
        <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_action_on_cat' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_action_on_cat' ) ); ?>">
           <option value="" <?php selected($wcw_action_on_cat,'' )?> >Show All Category:</option>       
           <option value="include" <?php selected($wcw_action_on_cat,'include' )?> >Include Selected Category:</option>       
           <option value="exclude" <?php selected($wcw_action_on_cat,'exclude' )?> >Exclude Selected Category:</option>
        </select> 
        <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_selected_categories' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_selected_categories' ) ); ?>[]" multiple>
                    <?php           
                    if($wcw_taxonomy_type){
                    $args = array( 'hide_empty=0' );
                    $terms = get_terms( $wcw_taxonomy_type, $args );
                    echo '<option value="" '.selected(true, in_array('',$wcw_selected_categories), false).'>None</option>';
                    if ( $terms ) {
                    foreach ( $terms as $term ) {
                        echo '<option value="'.$term->term_id.'" '.selected(true, in_array($term->term_id,$wcw_selected_categories), false).'>'.$term->name.'</option>';
                    }

                    }
                }

                ?>    
        </select>
        </p>
        <p>
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_count' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_hide_count' ) ); ?>" type="checkbox" value="1" <?php checked( $wcw_hide_count, 1 ); ?>>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_count' ) ); ?>"><?php _e( esc_attr( 'Hide Count' ) ); ?> </label> 
        </p>
        <p><a href="mailto:[email protected]">Contact to Author</a></p>
        <?php 
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @see WP_Widget::update()
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['wcw_title']                  = ( ! empty( $new_instance['wcw_title'] ) ) ? strip_tags( $new_instance['wcw_title'] ) : '';
        $instance['wcw_hide_title']             = ( ! empty( $new_instance['wcw_hide_title'] ) ) ? strip_tags( $new_instance['wcw_hide_title'] ) : '';
        $instance['wcw_taxonomy_type']          = ( ! empty( $new_instance['wcw_taxonomy_type'] ) ) ? strip_tags( $new_instance['wcw_taxonomy_type'] ) : '';
        $instance['wcw_selected_categories']    = ( ! empty( $new_instance['wcw_selected_categories'] ) ) ? $new_instance['wcw_selected_categories'] : '';
        $instance['wcw_action_on_cat']          = ( ! empty( $new_instance['wcw_action_on_cat'] ) ) ? $new_instance['wcw_action_on_cat'] : '';
        $instance['wcw_hide_count']             = ( ! empty( $new_instance['wcw_hide_count'] ) ) ? strip_tags( $new_instance['wcw_hide_count'] ) : '';
        return $instance;
    }
    /** plugin CSS **/
    function wcw_style_func_css()
    {
        $style='<style type="text/css">/* start wp categories widget CSS */.widget_wp_categories_widget{background:#fff; position:relative;}.wp_categories_widget h2{color:#4a5f6d;font-size:24px;font-weight:400;margin:0 0 25px;line-height:24px;text-transform:uppercase}.ve-cat-widget-div ul.ve-cat-widget-listing li{font-size: 16px;
    margin: 0px;
    border-bottom: 1px dashed #f0f0f0;
    position: relative;
    list-style-type: none;
    line-height: 35px;}.ve-cat-widget-div ul.ve-cat-widget-listing li:last-child{border:none;}.ve-cat-widget-div ul.ve-cat-widget-listing li a{display:inline-block;color:#007acc;transition:all .5s ease;-webkit-transition:all .5s ease;-ms-transition:all .5s ease;-moz-transition:all .5s ease}.ve-cat-widget-div ul.ve-cat-widget-listing li a:hover,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat a,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat span.post-count{color:#ee546c}.ve-cat-widget-div ul.ve-cat-widget-listing li span.post-count{height: 30px;
    min-width: 35px;
    text-align: center;
    background: #fff;
    color: #605f5f;
    border-radius: 5px;
    box-shadow: inset 2px 1px 3px rgba(0, 122, 204,.1);
    top: 0px;
    float: right;
    margin-top: 2px;}/* End category widget CSS*/</style>';
    echo $style;
    }
    function wcw_style_func()
    {
        add_action('wp_footer',array($this,'wcw_style_func_css'));
    }
    /** updtate plugins links using hooks**/
    // Add settings link to plugin list page in admin
    function wcw_add_settings_link( $links ) {
        $settings_link = '<a href="widgets.php">' . __( 'Settings Widget', 'mrwebsolution' ) . '</a> | <a href="mailto:[email protected]">' . __( 'Contact to Author', 'mrwebsolution' ) . '</a>';
        array_unshift( $links, $settings_link );
        return $links;
    }
}// class WpCategoriesWidget

// register WpCategoriesWidget widget
function register_wp_categories_widget() {
    register_widget( 'WpCategoriesWidget' );
}
add_action( 'widgets_init', 'register_wp_categories_widget'); 
/**************************************************************
                END CLASSS WpCategoriesWidget 
**************************************************************/

[![enter image description here][2]][2] As you see ordering by is not according to the B post type count.
I think we must change something in this line

$terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' => 'count', 'order' => 'DESC','hide_empty'=>0 ));

I have a custom taxonomy and two custom post types (A and B post types).
I created a taxonomy list and this list also display B posts type count of taxonomy. Taxonomy list is ordered by post count.

My problem is that the ordering of taxonomy is going according to the total post count ( total count of both A and B post types ).
I want ordering also to be according to B post type count of taxonomy.
Code based on WP Categories Widget
Please, need help this with my code:

<?php
/*
Plugin Name: WP Categories Widget
Plugin URI: http://www.mrwebsolution.in/
Description: It's a very simple plugin to display categories list in your website sidebar and you can define category list for your own custom taxonomy.
Author: MR Web Solution
Author URI: http://raghunathgurjar.wordpress
Version: 1.4
*


/*  Copyright 2018-19  wp-categories-widget  (email : [email protected])

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**************************************************************
                START CLASSS WpCategoriesWidget 
**************************************************************/
class WpCategoriesWidget extends WP_Widget {

    /**
     * Register widget with WordPress.
     */
    function __construct() {
        parent::__construct(
            'wp_categories_widget', // Base ID
            __( 'WP Categories list', 'mrwebsolution' ), // Name
            array( 'description' => esc_html__( 'Display categories list of all taxonomy post type', 'mrwebsolution' ), ) // Args
        );
        if(!is_admin())
        add_action('wcw_style',array($this,'wcw_style_func'));
        add_filter( "plugin_action_links_".plugin_basename( __FILE__ ), array(&$this,'wcw_add_settings_link') );
    }

    /**
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        echo $args['before_widget'];
        if ( ! empty( $instance['wcw_title'] ) && !$instance['wcw_hide_title']) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['wcw_title'] ) . $args['after_title'];
        }
        // add css      
        do_action('wcw_style','wcw_style_func');
        /** return category list */
        if($instance['wcw_taxonomy_type']){
            $va_category_HTML ='<div class="ve-cat-widget-div">';
            $va_category_HTML .='<ul class="ve-cat-widget-listing">';
                $args_val = array( 'hide_empty=0' );    
                $i=1;
                $excludeCat= $instance['wcw_selected_categories'] ? $instance['wcw_selected_categories'] : '';
                $wcw_action_on_cat= $instance['wcw_action_on_cat'] ? $instance['wcw_action_on_cat'] : '';
                if($excludeCat && $wcw_action_on_cat!='')
                $args_val[$wcw_action_on_cat] = $excludeCat;
                function wpse340250_term_count( WP_Term $term, $post_type) {
    $q_args = [
        'post_type' => $post_type,
        'nopaging' => true, // no limit, pagination
        'fields' => 'ids', // only return post id's instead of full WP_Post objects will speed up
        'tax_query' => array(
            array(
                'taxonomy' => $term->taxonomy,
                'field'    => 'term_id',
                'terms'    => $term->term_id,
            ),
        ),
    ];
    $term_count = get_posts($q_args);

    return count($term_count);
}

                $terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' => 'count', 'order' => 'DESC','hide_empty'=>0 ));
                if ( $terms ) { 
                    foreach ( $terms as $term ) {
                        $term_link = get_term_link( $term );
                        if ( is_wp_error( $term_link ) ) {
                        continue;
                        }

                    $carrentActiveClass=''; 

                    if($term->taxonomy=='category' && is_category())
                    {
                      $thisCat = get_category(get_query_var('cat'),false);
                      if($thisCat->term_id == $term->term_id)
                        $carrentActiveClass='class="active-cat"';
                    }

                    if(is_tax())
                    {
                        $currentTermType = get_query_var( 'taxonomy' );
                        $cat_icon = get_field('logo', $queried_object);
                        $termId= get_queried_object()->term_id;
                         if(is_tax($currentTermType) && $termId==$term->term_id)
                          $carrentActiveClass='class="active-cat"';


                    }   
                        $icon = get_field('logo', $term->taxonomy . '_' . $term->term_id); 
                        $va_category_HTML .= '<li class="logolar" '.$carrentActiveClass.'>' .'<a class="rownum">' .$i++. '</a>'. '</a>';
                        $va_category_HTML .= sprintf('<img src="%s" />', $icon) . '</a>';
                        $va_category_HTML .='<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>';
                        if (empty( $instance['wcw_hide_count'] )) {
                        $va_category_HTML .='<span class="post-count">'.wpse340250_term_count($term, 'sikayet').(' şikayət').'</span>';
                        }

                        $va_category_HTML .='</li>';
                    }
                }
            $va_category_HTML .='</ul></div>';
            echo $va_category_HTML;
            }   
        echo $args['after_widget'];
    }

    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $wcw_title                  = ! empty( $instance['wcw_title'] ) ? $instance['wcw_title'] : esc_html__( 'WP Categories', 'virtualemployee' );
        $wcw_hide_title             = ! empty( $instance['wcw_hide_title'] ) ? $instance['wcw_hide_title'] : esc_html__( '', 'virtualemployee' );
        $wcw_taxonomy_type          = ! empty( $instance['wcw_taxonomy_type'] ) ? $instance['wcw_taxonomy_type'] : esc_html__( 'category', 'virtualemployee' );
        $wcw_selected_categories    = (! empty( $instance['wcw_selected_categories'] ) && ! empty( $instance['wcw_action_on_cat'] ) ) ? $instance['wcw_selected_categories'] : esc_html__( '', 'virtualemployee' );
        $wcw_action_on_cat          = ! empty( $instance['wcw_action_on_cat'] ) ? $instance['wcw_action_on_cat'] : esc_html__( '', 'virtualemployee' );
        $wcw_hide_count             = ! empty( $instance['wcw_hide_count'] ) ? $instance['wcw_hide_count'] : esc_html__( '', 'virtualemployee' );
        ?>
        <p>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label> 
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_title' ) ); ?>" type="text" value="<?php echo esc_attr( $wcw_title ); ?>">
        </p>
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_hide_title' ) ); ?>" type="checkbox" value="1" <?php checked( $wcw_hide_title, 1 ); ?>>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_title' ) ); ?>"><?php _e( esc_attr( 'Hide Title' ) ); ?> </label> 
        </p>
        <p>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_taxonomy_type' ) ); ?>"><?php _e( esc_attr( 'Taxonomy Type:' ) ); ?></label> 
        <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_taxonomy_type' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_taxonomy_type' ) ); ?>">
                    <?php 
                    $args = array(
                      'public'   => true,
                      '_builtin' => false

                    ); 
                    $output = 'names'; // or objects
                    $operator = 'and'; // 'and' or 'or'
                    $taxonomies = get_taxonomies( $args, $output, $operator ); 
                    array_push($taxonomies,'category');
                    if ( $taxonomies ) {
                    foreach ( $taxonomies as $taxonomy ) {

                        echo '<option value="'.$taxonomy.'" '.selected($taxonomy,$wcw_taxonomy_type).'>'.$taxonomy.'</option>';
                    }
                    }

                ?>    
        </select>
        </p>
        <p>
        <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_action_on_cat' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_action_on_cat' ) ); ?>">
           <option value="" <?php selected($wcw_action_on_cat,'' )?> >Show All Category:</option>       
           <option value="include" <?php selected($wcw_action_on_cat,'include' )?> >Include Selected Category:</option>       
           <option value="exclude" <?php selected($wcw_action_on_cat,'exclude' )?> >Exclude Selected Category:</option>
        </select> 
        <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_selected_categories' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_selected_categories' ) ); ?>[]" multiple>
                    <?php           
                    if($wcw_taxonomy_type){
                    $args = array( 'hide_empty=0' );
                    $terms = get_terms( $wcw_taxonomy_type, $args );
                    echo '<option value="" '.selected(true, in_array('',$wcw_selected_categories), false).'>None</option>';
                    if ( $terms ) {
                    foreach ( $terms as $term ) {
                        echo '<option value="'.$term->term_id.'" '.selected(true, in_array($term->term_id,$wcw_selected_categories), false).'>'.$term->name.'</option>';
                    }

                    }
                }

                ?>    
        </select>
        </p>
        <p>
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_count' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'wcw_hide_count' ) ); ?>" type="checkbox" value="1" <?php checked( $wcw_hide_count, 1 ); ?>>
        <label for="<?php echo esc_attr( $this->get_field_id( 'wcw_hide_count' ) ); ?>"><?php _e( esc_attr( 'Hide Count' ) ); ?> </label> 
        </p>
        <p><a href="mailto:[email protected]">Contact to Author</a></p>
        <?php 
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @see WP_Widget::update()
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['wcw_title']                  = ( ! empty( $new_instance['wcw_title'] ) ) ? strip_tags( $new_instance['wcw_title'] ) : '';
        $instance['wcw_hide_title']             = ( ! empty( $new_instance['wcw_hide_title'] ) ) ? strip_tags( $new_instance['wcw_hide_title'] ) : '';
        $instance['wcw_taxonomy_type']          = ( ! empty( $new_instance['wcw_taxonomy_type'] ) ) ? strip_tags( $new_instance['wcw_taxonomy_type'] ) : '';
        $instance['wcw_selected_categories']    = ( ! empty( $new_instance['wcw_selected_categories'] ) ) ? $new_instance['wcw_selected_categories'] : '';
        $instance['wcw_action_on_cat']          = ( ! empty( $new_instance['wcw_action_on_cat'] ) ) ? $new_instance['wcw_action_on_cat'] : '';
        $instance['wcw_hide_count']             = ( ! empty( $new_instance['wcw_hide_count'] ) ) ? strip_tags( $new_instance['wcw_hide_count'] ) : '';
        return $instance;
    }
    /** plugin CSS **/
    function wcw_style_func_css()
    {
        $style='<style type="text/css">/* start wp categories widget CSS */.widget_wp_categories_widget{background:#fff; position:relative;}.wp_categories_widget h2{color:#4a5f6d;font-size:24px;font-weight:400;margin:0 0 25px;line-height:24px;text-transform:uppercase}.ve-cat-widget-div ul.ve-cat-widget-listing li{font-size: 16px;
    margin: 0px;
    border-bottom: 1px dashed #f0f0f0;
    position: relative;
    list-style-type: none;
    line-height: 35px;}.ve-cat-widget-div ul.ve-cat-widget-listing li:last-child{border:none;}.ve-cat-widget-div ul.ve-cat-widget-listing li a{display:inline-block;color:#007acc;transition:all .5s ease;-webkit-transition:all .5s ease;-ms-transition:all .5s ease;-moz-transition:all .5s ease}.ve-cat-widget-div ul.ve-cat-widget-listing li a:hover,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat a,.ve-cat-widget-div ul.ve-cat-widget-listing li.active-cat span.post-count{color:#ee546c}.ve-cat-widget-div ul.ve-cat-widget-listing li span.post-count{height: 30px;
    min-width: 35px;
    text-align: center;
    background: #fff;
    color: #605f5f;
    border-radius: 5px;
    box-shadow: inset 2px 1px 3px rgba(0, 122, 204,.1);
    top: 0px;
    float: right;
    margin-top: 2px;}/* End category widget CSS*/</style>';
    echo $style;
    }
    function wcw_style_func()
    {
        add_action('wp_footer',array($this,'wcw_style_func_css'));
    }
    /** updtate plugins links using hooks**/
    // Add settings link to plugin list page in admin
    function wcw_add_settings_link( $links ) {
        $settings_link = '<a href="widgets.php">' . __( 'Settings Widget', 'mrwebsolution' ) . '</a> | <a href="mailto:[email protected]">' . __( 'Contact to Author', 'mrwebsolution' ) . '</a>';
        array_unshift( $links, $settings_link );
        return $links;
    }
}// class WpCategoriesWidget

// register WpCategoriesWidget widget
function register_wp_categories_widget() {
    register_widget( 'WpCategoriesWidget' );
}
add_action( 'widgets_init', 'register_wp_categories_widget'); 
/**************************************************************
                END CLASSS WpCategoriesWidget 
**************************************************************/

[![enter image description here][2]][2] As you see ordering by is not according to the B post type count.
I think we must change something in this line

$terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' => 'count', 'order' => 'DESC','hide_empty'=>0 ));
Share Improve this question edited Nov 25, 2019 at 15:22 Ramin Mahmudov asked Jun 14, 2019 at 12:30 Ramin MahmudovRamin Mahmudov 511 silver badge12 bronze badges 4
  • 1 I recently investigated just this issue - getting 'count' from 'get_terms' by post type - and it's remarkably difficult to do. The feature has been nixed by contributors on WordPress Trac as all proposed solutions would consume too many resources on large sites. See this feature request: core.trac.wordpress/ticket/18106#comment:7 – Michelle Commented Jun 14, 2019 at 15:23
  • thank you for reference Michelle – Ramin Mahmudov Commented Jun 14, 2019 at 15:46
  • There are some workarounds in this q/a that might help. wordpress.stackexchange/questions/49026/… – Michelle Commented Jun 17, 2019 at 18:28
  • i tried.. not work :( – Ramin Mahmudov Commented Jun 17, 2019 at 21:07
Add a comment  | 

1 Answer 1

Reset to default 1

This question is a follow up of this question you asked earlier.
Here we handled getting count per posttype.

So you have all data, just not sorted correctly.
Looking at your code you have one big problem.
Getting and formatting data is done at the same time as you are outputting the data.
For maintainability (and readability) it is best to separate these as much as possible.

Your code did have unused variables. I removed stuff. So check the validity yourself. The core of the answer (sorting) should work. Do read the comments in the code to get a idea what it does and where what goes.

<?php

// functions probably should be kept in a different file like `functions.php`
function wpse340250_term_count( WP_Term $term, $post_type ) {
    $q_args     = [
        'post_type' => $post_type,
        'nopaging'  => true, // no limit, pagination
        'fields'    => 'ids', // only return post id's instead of full WP_Post objects will speed up
        'tax_query' => array(
            array(
                'taxonomy' => $term->taxonomy,
                'field'    => 'term_id',
                'terms'    => $term->term_id,
            ),
        ),
    ];
    $term_count = get_posts( $q_args );

    return count( $term_count );
}

// all raw data and other $instance stuff, no html variables
// just gather data.
$excludeCat        = $instance['wcw_selected_categories'] ? $instance['wcw_selected_categories'] : '';
$wcw_action_on_cat = $instance['wcw_action_on_cat'] ? $instance['wcw_action_on_cat'] : '';
$i                 = 1;

// get the terms you need
$terms        = get_terms( $instance['wcw_taxonomy_type'], array( 'orderby' => 'count', 'order' => 'DESC', 'hide_empty' => 0 ) );
$sorted_terms = [];
if ( $terms ) {
    foreach ( $terms as $term ) {
        $sorted_term = [
            'WP_Term'            => $term, // the global term
            'icon'               => get_field( 'logo', $term->taxonomy . '_' . $term->term_id ),
            'carrentActiveClass' => '',
            'count'              => (int) wpse340250_term_count( $term, 'my_B_custom_post_type' ),
            // everything you will need later here
        ];

        // here handle all dynamic checks add them to $sorted_term
        if ( $term->taxonomy == 'category' && is_category() ) {
            $thisCat = get_category( get_query_var( 'cat' ), false );
            if ( $thisCat->term_id == $term->term_id ) {
                $sorted_term['carrentActiveClass'] = 'class="active-cat"';
            }
        }

        // for the sake of getting to the core of the answer I left stuff out.


        // add the complete sorted_term to the collection
        $sorted_terms[] = $sorted_term;
    }

    // sort an array based on a sub value  https://stackoverflow/a/2477524/933065
    usort( $sorted_terms, function ( $a, $b ) {
        return $a['count'] - $b['count'];
    } );

}
// all done gathering data now we handle html output
?>
<?php if ( ! empty( $sorted_terms ) ) : ?>
    <div class="ve-cat-widget-div">
        <ul class="ve-cat-widget-listing">
            <?php foreach ( $sorted_terms as $sorted_term ) : ?>
                <li class="logolar" <?php echo $sorted_term['carrentActiveClass']; ?>>
                    <a class="rownum"><?php echo $i ++ ?></a>
                    <?php printf( '<img src="%s" />', $sorted_term['icon'] ) ?>
                    <a href="<?php echo esc_url( get_term_link( $sorted_term['WP_Term'] ) ) ?>"><?php echo $sorted_term['WP_Term']->name ?></a>
                    <?php if ( empty( $instance['wcw_hide_count'] ) ) : ?>
                        <span class="post-count"><?php echo $sorted_term['count'] ?></span>
                    <?php endif ?>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif ?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744970992a277486.html

最新回复(0)