Get current Category Name on a page which filters

2019-07-09 01:10发布

I'm successfully filtering all my WordPress posts (in a custom page template) by Likes (count) with a Custom Plugin (and meta_key) which also let me filter the most liked posts in a specific category with the following

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');

The Category List to Filter the Posts for each Category (works fine)

<?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 } ?>

The url after filtering the posts for example - looks like

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

Any idea how to echo only the current category name on the current page? In the case of the example it would be "New Post Category"

1条回答
狗以群分
2楼-- · 2019-07-09 01:41

There is 3 possibilities (the taxonomy for WP categories is category):

1) An ID - If $_GET['category'] is a WP category term ID you will use:

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 - If $_GET['category'] is a WP category term SLUG you will use:

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 - If it is already a WP category terme NAME just use:

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

查看更多
登录 后发表回答