Come filtrare get_posts per ottenere solo articoli con formato standard in WordPress

13 apr 2012, 14:34:00
Visualizzazioni: 17.1K
Voti: 11

Sto cercando di creare un archivio che mostri solo i miei articoli con formato "standard" (escludendo formati come link, aside, quote, ecc.).

Come potrei implementare has_post_format( 'standard' ), o qualcosa di simile, nel codice qui sotto?

Non sono riuscito a trovare una query per get_posts che richieda solo specifici tipi di formato.

<?php    
    // Ottieni i post
    $myposts = get_posts('numberposts=-1&orderby=post_date&order=DESC');     
?>

<?php foreach($myposts as $post) : ?>   

<?php    
    // Prepara le variabili del post
    setup_postdata($post);

    $year = mysql2date('Y', $post->post_date);
    $month = mysql2date('n', $post->post_date);
    $day = mysql2date('j', $post->post_date);    
?>

<p>
    <span class="the_article">
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </span>
    &nbsp;&nbsp;&nbsp;
    <span class="the_day">
        <?php the_time('j F Y'); ?>
    </span>
</p>

<?php endforeach; ?>

Le mie competenze in PHP sono a livello base, quindi qualsiasi aiuto sarebbe molto apprezzato.

0
Tutte le risposte alla domanda 4
4
22

In realtà non puoi passare un argomento relativo alla tassonomia a get_posts(). (Modifica: in realtà, sì che puoi. Il Codex è solo un po' poco chiaro. Guardando il codice sorgente, get_posts() è, in sostanza, solo un wrapper per WP_Query().) Puoi passare chiavi/valori meta e tipi di post, ma non tassonomie come il formato del post. Quindi per questa riga:

$myposts = get_posts('numberposts=-1&orderby=post_date&order=DESC');

Consiglierei di usare WP_Query() invece di get_posts():

$myposts = new WP_Query( array(
    'tax_query' => array(
        array(                
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => array( 
                'post-format-aside',
                'post-format-audio',
                'post-format-chat',
                'post-format-gallery',
                'post-format-image',
                'post-format-link',
                'post-format-quote',
                'post-format-status',
                'post-format-video'
            ),
            'operator' => 'NOT IN'
        )
    )
) );

Nota: sì, sono molti array annidati. Le query tassonomiche possono essere complicate così.

Il passo successivo è modificare le istruzioni di apertura/chiusura del loop. Cambia queste:

<?php foreach($myposts as $post) : ?>

    <?php /* markup del loop qui */ ?>

<?php endforeach; ?>

...in questo:

<?php if ( $myposts->have_posts() ) : while ( $myposts->have_posts() ) : $myposts->the_post(); ?>

    <?php /* markup del loop qui */ ?>

<?php endwhile; endif; ?>

<?php wp_reset_postdata(); ?>

Il tuo markup effettivo del loop dovrebbe rimanere lo stesso, tranne per il fatto che non hai più bisogno di chiamare setup_postdata( $post ):

<?php        
    $year = mysql2date('Y', $post->post_date);
    $month = mysql2date('n', $post->post_date);
    $day = mysql2date('j', $post->post_date);    
?>

<p>
    <span class="the_article">
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </span>
    &nbsp;&nbsp;&nbsp;
    <span class="the_day">
        <?php the_time('j F Y'); ?>
    </span>
</p>

Quindi, mettendo tutto insieme:

<?php
// Esegui la query solo per i post con
// formato "standard", il che richiede
// *escludere* tutti gli altri
// formati, poiché né la tassonomia
// "post_format" né il termine tassonomico
// "post-format-standard" sono applicati
// ai post senza formati definiti
$myposts = new WP_Query( array(
    'tax_query' => array(
        array(                
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => array( 
                'post-format-aside',
                'post-format-audio',
                'post-format-chat',
                'post-format-gallery',
                'post-format-image',
                'post-format-link',
                'post-format-quote',
                'post-format-status',
                'post-format-video'
            ),
            'operator' => 'NOT IN'
        )
    )
) );

// Apri il loop
if ( $myposts->have_posts() ) : while ( $myposts->have_posts() ) : $myposts->the_post(); ?>

    $year = mysql2date('Y', $post->post_date);
    $month = mysql2date('n', $post->post_date);
    $day = mysql2date('j', $post->post_date);    
    ?>

    <p>
        <span class="the_article">
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </span>
        &nbsp;&nbsp;&nbsp;
        <span class="the_day">
            <?php the_time('j F Y'); ?>
        </span>
    </p>  
    <?php 

// Chiudi il loop
endwhile; endif;

// Ripristina i dati $post alla query predefinita
wp_reset_postdata();
13 apr 2012 16:14:24
Commenti

grazie, hai reso davvero semplice la comprensione per un principiante spiegandolo in modo chiaro. Immagino che, dato che uso solo i formati aside, link e post standard, posso effettivamente saltare il resto.

daba daba
14 apr 2012 00:37:46

Sì; dovresti includere solo i formati di post per i quali hai abilitato il supporto.

Chip Bennett Chip Bennett
14 apr 2012 00:43:06

get_posts() utilizza effettivamente WP_Query, quindi ovviamente puoi passare query di tassonomia, basta passarli come array e non come stringa di query.

shabushabu shabushabu
14 apr 2012 13:45:48

@shabushabu grazie per il tuo contributo. Ho aggiornato la mia risposta.

Chip Bennett Chip Bennett
14 apr 2012 18:00:51
1

I formati dei post sono semplicemente termini predefiniti in una tassonomia chiamata post_format, quindi dovresti essere in grado di utilizzare la gerarchia dei template di WP per creare archivi per i formati dei post. Basta creare un file chiamato taxonomy-post_format-post-format-standard.php nella root del tuo tema e quel file verrà utilizzato per visualizzare tutti i tuoi post standard. Puoi sostituire 'standard' con qualsiasi altro nome di formato, come aside, link o video, ad esempio taxonomy-post_format-post-format-video.php. Questo funziona anche per qualsiasi altra tassonomia, purché tu rispetti questo formato: taxonomy-{NOME_TAXONOMIA}-{NOME_TERMINE}.php

Se vuoi mostrare i formati dei post con un loop personalizzato, ad esempio nella tua sidebar o all'interno di un template di pagina, allora puoi usare la tax query di @kaiser. Basta sostituire la tassonomia con post_format e gli slug con post-format-{NOME_FORMATO}.

13 apr 2012 15:34:58
Commenti

grazie, ma sto cercando di creare gli archivi all'interno di un template di pagina, quindi opterò per una delle altre soluzioni :)

daba daba
14 apr 2012 00:35:48
0

Per due diverse tassonomie. Per una singola, puoi omettere l'argomento relation.

$args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'movie_janner',
            'field' => 'slug',
            'terms' => array( 'action', 'commedy' ) // Singoli termini come stringa - multipli come array
        ),
        array(
            'taxonomy' => 'actor',
            'field' => 'id',
            'terms' => array( 103, 115, 206 ),
            'operator' => 'NOT IN'
        )
    )
);
13 apr 2012 15:02:00
1
-1

Puoi fare un trucco come questo:

<?php 
while( have_posts() ) : the_post();
get_post_format()==false? get_template_part( 'loop', 'posts' ) : false;
endwhile;
?>

Questo perché get_post_format() per il formato post standard restituisce false. http://codex.wordpress.org/Function_Reference/get_post_format

3 gen 2014 14:15:16
Commenti

effettivamente questo funziona, ma si possono creare problemi quando si considera l'impaginazione. Se fai qualcosa come 'posts_per_page' => 6 e hai 4 post con template NON standard, vedrai solo 2 post invece dei 6 che dovrebbero essere visibili. Filtrare la query è il modo corretto da seguire..

honk31 honk31
20 lug 2015 22:16:40