在按类别和自定义过滤帖子的页面上获取当前类别名称 meta_key

Get current Category Name on a page which filters posts by Category and custom meta_key

我使用自定义插件(和 meta_key)通过点赞(计数)成功过滤了我所有的 WordPress 帖子(在自定义页面模板中),这也让我过滤了特定中最喜欢的帖子类别如下

if (isset($_GET['category'])) {
    $args = array(
    'meta_key' => '_recoed',
    'meta_compare' => '>',
    'meta_value' => '0',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'category_name' => sanitize_text_field($_GET['category']),
    'paged' => $paged
    );
} 

query_posts($args);

get_template_part('index');

用于过滤每个类别帖子的类别列表(工作正常)

<?php $categories = get_categories('exclude=' . implode(',', my_blog_cats()) . ', 1'); ?>

<?php if ($categories) { ?>

<?php $categories = get_categories(); ?>

<?php foreach($categories as $category) { ?>
    <li>
        <a class="popular-categories" href="<?php echo get_permalink(); ?>?category=<?php echo $category->category_nicename; ?>"><?php echo $category->name; ?></a> 
    </li>
<?php endforeach; ?>

<?php } ?>

过滤帖子后的 url 例如 - 看起来像

.../hot-posts/?category=new-posts-category

知道如何只回显当前页面上的当前类别名称吗? 在这个例子中,它将是 "New Post Category"

有 3 种可能性 (WP 类别的分类法是 category:

1) ID - 如果 $_GET['category'] 是 WP category term ID 您将使用:

if( isset($_GET['category'] ) && term_exists( intval($_GET['category']), 'category' ) ){
    $term = get_term( intval($_GET['category']), 'category' );
    echo '<p>' . $term->name . '</p>';
}

2) A SLUG - 如果 $_GET['category'] 是 WP category term SLUG 你将使用:

if( isset($_GET['category'] ) && term_exists( sanitize_text_field($_GET['category']), 'category' ) ){
    $term = get_term_by( 'slug', sanitize_text_field($_GET['category']), 'category' );
    echo '<p>' . $term->name . '</p>';
}

3) A NAME - 如果它已经是 WP category terme NAME 只需使用:

if( isset($_GET['category'] ) && term_exists( sanitize_text_field($_GET['category']), 'category' ) )
    echo '<p>' . sanitize_text_field($_GET['category']) . '</p>';

But dont use sanitize_title() on WP category terme NAME as it will become a term SLUG