仅在有帖子时显示类别

时间:2015-10-06 05:58:24

标签: php wordpress categories sticky featured

由于许多不同的原因,我被迫停用WordPress上的粘贴帖子功能。我仍然需要这个功能。这意味着我需要一个解决方法。我需要在Feed的顶部显示一个帖子,我需要为撰写帖子的用户尽可能轻松地创建帖子。

注意:我使用的是Visual Composer。

我认为解决方法是通过Visual Composer或侧边栏添加新容器并调用类别。只有在该类别上有任何帖子时,才能看到这个新的侧边栏/容器。我一直在寻找功能,查询,插件等来做到这一点,但没有成功。

我找到Featured Post WidgetFeatured Category Widget,但我认为它们不是我需要的。

1 个答案:

答案 0 :(得分:2)

get_terms 的挂钩只有在有帖子时才会显示条款/类别

在WP主题的functions.php

中添加此代码

E.g (domain.com/wp-content/themes/yourThemeName/functions.php)

add_filter('get_terms', 'get_terms_filter', 10, 3);
function get_terms_filter( $terms, $taxonomies, $args )
{
    global $wpdb;
    $taxonomy = $taxonomies[0];
    if ( ! is_array($terms) && count($terms) < 1 )
        return $terms;
    $filtered_terms = array();
    foreach ( $terms as $term )
    {
        $result = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts p JOIN $wpdb->term_relationships rl ON p.ID = rl.object_id WHERE rl.term_taxonomy_id = $term->term_id AND p.post_status = 'publish' LIMIT 1");
        if ( intval($result) > 0 )
            $filtered_terms[] = $term;
    }
    return $filtered_terms;
}

用于忽略主要查询中前端集ignore_sticky_poststrue的粘贴帖子

add_action('pre_get_posts', '_ignore_sticky');

function _ignore_sticky($query)
{
    // Only for Front end
    if (!is_admin() && $query->is_main_query())
        $query->set('ignore_sticky_posts', true);
}