1
votes

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

1 Answers

2
votes

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