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

时光怂恿深爱的人放手 提交于 2019-12-14 02:11:27

问题


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:


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



来源:https://stackoverflow.com/questions/48525133/get-current-category-name-on-a-page-which-filters-posts-by-category-and-custom-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!