Wordpress : How to display tags from a specific category?

时间:2017-06-09 12:38:23

标签: php wordpress

I tried many solutions, but not good in my case. Do you have an idea to display "best tags" (most use of last 30 days) from a specific category with function get_terms() of Wordpress ?

<?php $wpdb->show_errors(); ?>
<?php
global $wpdb;
$term_ids = $wpdb->get_col(
"SELECT term_id FROM $wpdb->term_taxonomy
INNER JOIN $wpdb->term_relationships ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
INNER JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= $wpdb->posts.post_date"
                    );

if(count($term_ids) > 0){
$tags = get_terms(array(
    'orderby' => 'count', 
    'order' => 'DESC', 
    'number' => 8, 
    'include' => $term_ids,
));

foreach ( (array) $tags as $tag ) { ?>
    <li>
        <a href="<?php echo get_tag_link($tag->term_id); ?>" rel="tag" class="text-center">
            <img src="<?php the_field('image', $tag); ?>" class="trend-artist-img">
            <p><?php echo $tag->name ?></p>
        </a>
    </li>
<?php }} ?>

With this code, I have the complete list of the "best tags" but not for a specific category.

The category what I need have the ID : 18.

Thanks!

2 个答案:

答案 0 :(得分:0)

您可以通过将分类法传递给get_terms来按分类法进行过滤:

`$tags = get_terms(array( 
        'orderby' => 'count', 
        'order' => 'DESC', 
        'number' => 8, 
        'include' => $term_ids,
        'taxonomy' => 'my_category', // e.g 'post_tag'
    )); 

或者,要按 中的特定类别进行过滤,分类标准会传递&#39;名称&#39; to get_terms:

`$tags = get_terms(array( 
        'orderby' => 'count', 
        'order' => 'DESC', 
        'number' => 8, 
        'include' => $term_ids,
        'name' => 'my_category_name', 
    ));

这些可以合并。这有帮助吗?

答案 1 :(得分:0)

我已经重新阅读了您的问题,我认为您尝试做的事情可能无法通过单个查询完成。

问题在于标签和类别都应用于帖子而不是相互之间,因此两者之间没有简单的关系。您可以为每个最佳标记执行新的WP_Query,以检查是否有任何帖子同时包含标记和类别,但这将非常缓慢且效率低下。或者您可以执行WP_Query以获取具有该类别和任何最佳标记的所有帖子,然后使用该查询的结果来确定哪些(如果有)最佳标记未被使用。

这些选项看起来比它们对我的价值更大!