WordPress – slider and featured posts with given category name

Question

My WordPress 4.1 web site supports featured content and header slider. I’ve added a child theme. Posts, I want to show, have the ‘featured’ content tag and image, and are organized into multi-leveled categories. In the slider I want to present only those posts and pages (!) that have the given top level category slug. All other posts on its children categories should be excluded. How to configure the slider to use only the posts and pages with the given category and nothing more?

Answer

1. Get the category id from category slug name

$idcat = get_category_by_slug('slugname')->term_id;

2. In your child theme, add to your functions.php the code that returns the value of the filter defined for yourtheme_get_featured_posts.

add_filter('yourtheme_get_featured_posts', myfunction($posts));

For example, the slider contains only published posts and pages assigned to category ‘business’. No children categories are included:

// Header slider with featured posts and pages with category slug 'business'
add_filter( 'twentyfourteen_get_featured_posts', function( $posts ){
    $idcat = get_category_by_slug('business')->term_id;
    $postsnew = get_posts(array(
        // option: category slug + children:
        // 'category_name' => 'business',
        // option: category slug - children
        'category__in' => $idcat,
        // published posts only
        'post_status' => 'publish',
        // max 8 posts in slider
        'posts_per_page' => 8,
        // option: include posts + pages
        'post_types' => array( 'post', 'page' ),
        // optional custom meta: position number
        'meta_key'=> 'position',
        'orderby' => 'meta_value_num title',  
        // order: ASC by position number, title
        'order' => 'ASC'  
    ));
    if ( count($postsnew) > 0 ) {
        return $postsnew;
    } else {
        return $posts;
    }
}, PHP_INT_MAX );