Come visualizzare i post di una categoria specifica utilizzando una Query personalizzata in WordPress?
Ciao, voglio visualizzare una categoria specifica da una query personalizzata in WordPress. Il mio codice funziona bene e ottiene gli ultimi 4 post, ma ora vorrei recuperare una categoria specifica. Il mio codice è qui sotto, grazie:
global $wpdb;
// Seleziona ID, titolo e excerpt degli ultimi 4 post pubblicati
$posts = $wpdb->get_results('SELECT ID, post_title AS title, post_excerpt AS excerpt FROM '.$wpdb->posts.' WHERE post_type = "post" AND post_status = "publish" ORDER BY post_date DESC LIMIT 4');
Ed ecco il mio codice completo:
global $wpdb;
// Seleziona post di una categoria specifica
$posts = $wpdb->get_results('SELECT ID, post_title AS title, post_excerpt AS excerpt FROM '.$wpdb->posts.'
WHERE post_type = "post" AND post_status = "publish" ORDER BY post_date cat = "category_id" DESC LIMIT 4');
$items = array();
foreach ($posts as $post) {
// Prepara array con i dati del post
$item = array();
$item['title'] = get_the_title($post->ID);
$item['url'] = get_permalink($post->ID);
$item['desc'] = $post->excerpt;
$item['image'] = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
$item['thumb'] = get_post_meta($post->ID, 'Thumbnail', true);
$items[] = $item;
}
return $items;
Ora voglio aggiungere l'output finale, vedi il codice qui sotto:
" id="nav-fragment-"> "> " class="ui-tabs-panel" style=""> " alt="" /> " >" >Leggi di più
il modo consigliato è:
<?php
$query = new WP_Query('category_name=Category&posts_per_page=4');
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
if (has_post_thumbnail()) {
?>
<a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a>
<?php
}
?>
<h2><a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php
the_excerpt(); // oppure the_content(); per il contenuto completo del post
endwhile;endif;
?>

Tutto a posto, anche il primo suggerimento di @Ammu funzionava. Ho dovuto modificare i valori dell'array per farli corrispondere all'istruzione, ecco il codice:
global $wpdb;
$cat_id = 10;
$posts = $wpdb->get_results("SELECT
ID, post_title AS title, post_excerpt AS excerpt FROM $wpdb->posts p
JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
WHERE p.post_type='post'
AND p.post_status = 'publish'
AND tt.taxonomy = 'category'
AND t.term_id = $cat_id
ORDER BY post_date DESC LIMIT 4");

Va notato che bypassare l'API ed effettuare query direttamente potrebbe avere conseguenze indesiderate, rimuovendo la possibilità di fare tutte le cose che l'API consente - filtri, azioni, ecc.. Dovresti sempre utilizzare l'API (WP_Query
) quando possibile e non una query SQL diretta.
