图片待添加
图片待添加

WordPress主题开发:显示WordPress当前分类所有文章标签

2020-02-26 21:42 分类:WordPress主题开发制作教程 阅读(次阅读) 标签:,,

我们很多WordPress网站都有本站的热门标签或者所有标签,但是所有页面的右侧的标签都是没有变化的.
可以通过本办法显示当前分类下面的所有标签.

你可以自己修改WordPress主题,可以显示在分类页面的头部,也可以显示在侧边栏.
当访客访问不同分类的时候,侧边栏的标签会自动变换成相应的.
我想这样利于WordPress SEO,也可能吸引访客看到自己感兴趣的内容,毕竟每个分类的主题鲜明,那么分类的标签也会比较集中.

WordPress主题开发:显示WordPress当前分类所有文章标签

在你的WordPress主题的 functions.php里面添加如下代码:

function get_category_tags($args) {
    global $wpdb;
    $tags = $wpdb->get_results
    ("
        SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name
        FROM
            $wpdb->posts as p1
            LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_ID
            LEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
            LEFT JOIN $wpdb->terms as terms1 ON t1.term_id = terms1.term_id,
            $wpdb->posts as p2
            LEFT JOIN $wpdb->term_relationships as r2 ON p2.ID = r2.object_ID
            LEFT JOIN $wpdb->term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
            LEFT JOIN $wpdb->terms as terms2 ON t2.term_id = terms2.term_id
        WHERE
            t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms1.term_id IN (".$args['categories'].") AND
            t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
            AND p1.ID = p2.ID
        ORDER by tag_name
    ");
    $count = 0;
    if($tags) {
        foreach ($tags as $tag) {
            $mytag[$count] = get_term_by('id', $tag->tag_id, 'post_tag');
            $count++;
        }
    } else {
      $mytag = NULL;
    }
    return $mytag;
}

然后保存并上传覆盖WordPress主题的 functions.php.

然后我们来修改: archive.php [archive.php是WordPress主题的分类模板的名称]

你可以添加在分类页面的头部,也可以显示在侧边栏,这个就需要一定的WordPress主题开发基础了.

<?php
    $cat= single_cat_title('', false);
    $args = array( 'categories' => get_cat_ID($cat));
    $tags = get_category_tags($args);
    $content .= "<ul class='cat-tag-ul'>";
    if(!empty($tags)) {
        foreach ($tags as $tag) {
            $content .= "<li><a href=\"".get_tag_link($tag->term_id)."\">".$tag->name."</a></li>";
        }
    }
    $content .= "</ul>";
    echo $content;
?>

接下来需要在WordPress主题的style.css为.cat-tag-ul{} 与.cat-tag-ul li{}添加合适的样式.

 


本文地址: https://www.wpyi.com/dangqian-fenlei-biaoqian.html