【问题标题】:make a wordpress tag cloud of an specific category link to a list of articles of that category & tag制作特定类别的wordpress标签云链接到该类别和标签的文章列表
【发布时间】:2014-10-06 17:04:24
【问题描述】:

我需要显示一个特定类别的所有标签的标签云,所以我使用一个函数来检索所有标签:

function tags_by_cat($cat_id)
{
$custom_query = new WP_Query("posts_per_page=-1&cat={$cat_id}");
if ($custom_query->have_posts()) :
    while ($custom_query->have_posts()) : $custom_query->the_post();
        $posttags = get_the_tags();
        if ($posttags) {
            foreach($posttags as $tag) {
                $all_tags[] = $tag->term_id;
            }
        }
    endwhile;
endif;

$tags_arr = array_unique($all_tags);
$tags_str = implode(",", $tags_arr);

return $tags_str;
}

然后我在模板中生成标签云,例如类别 33:

wp_tag_cloud( array('smallest'=>8,'largest'=>22,'include'=>tags_by_cat(33)));

问题是,虽然它工作正常,但此云的每个标签都链接到包含该标签的所有文章的列表,但我需要按原始类别过滤此列表。 Wordpress 已经可以做到这一点(即http://www.website.com/?cat=33&tag=computing),但我找不到如何在云的 url 中引入 url 参数。我也在使用帖子名称永久链接,所以这可能会使事情变得更复杂。

是否有一些参数可以做我想做的事,或者我可以用某种钩子来做吗?我打算重新创建自己的 wp_tag_cloud,但我不太确定从哪里开始

【问题讨论】:

    标签: php wordpress tag-cloud


    【解决方案1】:

    好吧,我终于创建了一个似乎可以正常工作的钩子,对于那些可能有同样问题的人:

    add_filter ( 'wp_tag_cloud', 'tag_cloud_add_cat' );
    function tag_cloud_add_cat( $taglinks ) {
        if (is_category())
        {
            $category = get_category( get_query_var( 'cat' ) );
            $current_cat_slug = $category->slug;
    
            $tags = explode('</a>', $taglinks);     
            $regex = "#(.*href=\')(.*)(' class.*)#e";       
                foreach( $tags as $tag ) {          
                $varin=strpos($tag,"?")!==false?'&':'?';
                $tagres[] = preg_replace($regex, "'$1$2{$varin}category_name={$current_cat_slug}$3'", $tag );
                }
            $taglinks = implode('</a>', $tagres);
        }
        return $taglinks;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多