hello world!
27 Dicembre 2017

Widget "Post recenti" di WordPress, target in base a categoria

Oggi vediamo come filtrare, in base alla categoria, i post da visualizzare nel widget "Post recenti".

Tramite il seguente filtro possiamo effettuare anche altre modifiche, le vedremo meglio in futuro. Come sempre inseritelo all'interno di function.php o di un plugin creato ad hoc.

1. Filtro per INCLUDERE articoli in una o più categorie

function filtro_categoria($args) {
    return array(
        'posts_per_page'      => 10, //il numero di post
        'no_found_rows'       => true,
        'post_status'         => 'publish', 
        'ignore_sticky_posts' => true,
        'cat'                 => 1 //l'ID della categoria da includere
    );
}
add_filter( 'widget_posts_args', 'filtro_categoria');
function filtro_categoria($args) {
    return array(
        'posts_per_page'      => 10, //il numero di post
        'no_found_rows'       => true, 
        'post_status'         => 'publish', 
        'ignore_sticky_posts' => true,
        'cat'                 => array(1, 2, ecc) //gli ID delle categorie da includere
    );
}
add_filter( 'widget_posts_args', 'filtro_categoria');

2. Filtro per ESCLUDERE gli articoli all'interno di una o più categorie

function filtro_categoria($args) {
    return array(
        'posts_per_page'      => 10, //il numero di post
        'no_found_rows'       => true, 
        'post_status'         => 'publish', 
        'ignore_sticky_posts' => true,
        'category__not_in'    => 1 //l'ID della categoria da escludere
    );
}
add_filter( 'widget_posts_args', 'filtro_categoria');
function filtro_categoria($args) {
    return array(
        'posts_per_page'      => 10, //il numero di post
        'no_found_rows'       => true, 
        'post_status'         => 'publish', 
        'ignore_sticky_posts' => true,
        'category__not_in'    => array(1, 2, ecc) //gli ID delle categorie da escludere
    );
}
add_filter( 'widget_posts_args', 'filtro_categoria');

Come potete vedere sono presenti sia i filtri per includere o escludere una sola categoria, sia per includere o escludere più categorie.

Per qualsiasi problema, consiglio ecc... scriveteci un commento o contattateci direttamente.

Aggiornamento: ho rilasciato un plugin, scaricabile dalla directory WordPress, che consente di scegliere le categorie dei post da includere. Potete scaricarlo dal box qui sotto.