Wordpress get_posts per categoria
Ho il seguente pezzo di codice:
$args = array(
'posts_per_page' => -1,
'category' => 7,
'orderby' => 'name',
'order' => 'ASC',
'post_type' => 'product'
);
$posts = get_posts($args);var_dump($posts);
Questo dovrebbe restituire un post che so essere nella categoria, ma non lo fa. Se ometto l'argomento 'category', ottengo tutti i prodotti, quindi so che normalmente dovrebbe funzionare. Se cambio la categoria in 1 e tolgo il mio tipo di post personalizzato (product), ottengo i miei post predefiniti.
Non riesco a capire qual è il problema. Qualcuno riesce a individuare dove sta l'errore?

Con ogni probabilità stai utilizzando una tassonomia personalizzata, e non la tassonomia predefinita category
. Se questo è il caso, allora i parametri della categoria non funzioneranno. Avrai bisogno di una tax_query
per interrogare i post da uno specifico termine. (Ricorda, get_posts
utilizza WP_Query
, quindi puoi passare qualsiasi parametro da WP_Query
a get_posts
)
$args = [
'post_type' => 'product',
'tax_query' => [
[
'taxonomy' => 'my_custom_taxonomy',
'terms' => 7,
'include_children' => false // Rimuovi se hai bisogno di post dai termini figli del termine 7
],
],
// Resto dei tuoi argomenti
];
RISORSE AGGIUNTIVE

<ul>
<?php
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();?>
</ul>
Forse questo potrà aiutarti.
Grazie

Da quale 'post_type' otterrà ora i links, 5 nel tuo caso? Secondo me vuole il contenuto dei prodotti (come ho capito un CPT) e niente dai post regolari.

passa il tuo ID della categoria negli argomenti e dai post regolari otterrai 5 post.

Per favore leggi la sua domanda, non ho sempre ragione ma in questo caso lui vuole 'qualcosa' da un Custom Post Type con il nome Product.

Charles ha ragione in questo caso. So come ottenere i dati una volta che ho i miei post. Il problema era che non stavo ottenendo i miei custom post :)
