Filter wp_list_categories from one custom post type

亡梦爱人 提交于 2019-12-12 05:35:30

问题


I have 2 custom post types called 'project' and 'client' that share a taxonomy called 'sector'.

if (!is_taxonomy('sector')) {
        register_taxonomy(
        'sector', array('project', 'client'), array(
        'hierarchical' => true,
        'label' => 'Sector',
        'query_var' => true,
        'rewrite' => array( 'slug' => 'sector' ),
        'with_front' => false
        ) );

        wp_insert_term('Health', 'sector');
        wp_insert_term('Clubs', 'sector');
        wp_insert_term('Commercial', 'sector');     
    }

I have created a taxonomy archive template with a sidebar nav that lists links to my taxonomy archives using:

//list terms in a given taxonomy using wp_list_categories 

    $orderby      = 'name'; 
    $show_count   = 1;      // 1 for yes, 0 for no
    $pad_counts   = 0;      // 1 for yes, 0 for no
    $hierarchical = 0;      // 1 for yes, 0 for no
    $show_option_none='';
    $title        = '';

    $args_sector = array(
      'taxonomy'     => 'sector',
      'orderby'      => $orderby,
      'show_count'   => $show_count,
      'pad_counts'   => $pad_counts,
      'hierarchical' => $hierarchical, 
      'title_li'     => $title
    );


<ul id="sideNav" class="rightSubMenu">   
      <h3 class="rightSubNav">SECTOR</h3>
      <ul id="sideNav" class="rightSubMenu">
        <?php wp_list_categories( $args_sector ); ?>
      </ul>

</ul>

The problem is if I have a project that is linked to 'clubs' and a client that is linked to 'clubs' the output count shows 2. Also the archive page shows 2 posts - 1 for project and one for client. But there is only one project.

I am mainly concerned with the project page and would like to filter the results by my 'project' post type. I looked through the codex and the wp_list_categories function doesn't seem to accept a parameter to do this.

Can anyone help? Is there a better way to do this?


回答1:


I have had a similar problem. I did this by cloning the wp_list_categories function, giving it a different name and putting in this code after the line: $categories=get_categories($r):

 foreach ($categories as $key => $category){
        $temp = array ( 'post_type'=>$r['type'], 'tax_query' => array(
            array (
                'taxonomy' => $category->taxonomy,
                'field' => 'slug',
                'terms' => $category->slug
            )

        )
            );
        $pauli = new wp_query($temp);
        if($pauli->post_count==0){
            unset($categories[$key]);
        }
    }

As you can see, it removes categories that do not have any of the post type you need, and then continues the process as wp_list_categories does normally.



来源:https://stackoverflow.com/questions/5287383/filter-wp-list-categories-from-one-custom-post-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!