douhanzhen8927 2015-10-06 05:58
浏览 55

仅在有帖子时显示类别

For many different reasons I was forced to deactivate the sticky posts function on WordPress. Still I need this function. This means that I need a workaround. I need to show a post on the top of the feed and I need it to be made as easily as possible for the user that is writing the post.

NOTE: I am using Visual Composer.

I thought that a workaround for this would be to add a new container via Visual Composer or a sidebar and call for a category. This new sidebar/container would then only be visible if there were any posts on that category. I have been searching for a function, query, plugin, etc to do this, but with no success.

I have found Featured Post Widget and Featured Category Widget but I don't think that they are what I need.

  • 写回答

1条回答 默认 最新

  • douken1726 2015-10-06 06:34
    关注

    Hook with get_terms will display a terms/category only when it has posts

    Add this code in WP theme's 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;
    }
    

    For ignore sticky posts on frontend set ignore_sticky_posts to true in main query

    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);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口