Query più efficiente per visualizzare post nella stessa sottocategoria?
30 ott 2014, 16:04:12
Visualizzazioni: 297
Voti: 0
[MODIFICA: Vedi il mio commento sotto, potrei essere stato ingannato dalla cache di Chrome che mostrava una versione precedente di questo codice. Ora sembra funzionare abbastanza velocemente. Lascio la domanda nel caso qualcuno veda un modo migliore ma non preoccupatevi troppo se non ci sono soluzioni - chiuderò tra qualche giorno.]
Molte persone hanno pubblicato codice come questo per mostrare 'post correlati' nella sidebar, e l'ho adattato in uno shortcode. Funziona, ma impiega 1-2 secondi per caricare su localhost. Potrei aggiungere la cache transient ma dato che è una query per tipo di post non credo che aiuterebbe molto. C'è un modo più efficiente per scrivere questo codice?
// SHORTCODE PER MOSTRARE POST CORRELATI NELLA SIDEBAR
// Mostra post nella stessa sottocategoria del post corrente
// utilizzo: [related_posts posts="5"]
add_shortcode( 'related_posts', 'mkm_related_posts_shortcode' );
function mkm_related_posts_shortcode( $atts ) {
ob_start();
$current_post_id = get_queried_object_id();
// definisce gli attributi e i loro valori predefiniti
extract( shortcode_atts( array (
'type' => 'post',
'order' => 'asc',
'orderby' => 'menu_order',
'posts' => '3',
), $atts ) );
$categories = get_the_category($current_post_id);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) {
// cerca solo le sottocategorie correnti
if ( $individual_category->parent !== 0 ) {
$category_ids[] = $individual_category->term_id;
}
}
}
$options = array(
'post_type' => $type,
'order' => $order,
'orderby' => $orderby,
'posts_per_page' => $posts,
'category__in' => $category_ids,
'post__not_in' => array($current_post_id),
);
$related_query = new WP_Query( $options );
$output = '';
// esegue il loop basato sulla query
if ( $related_query->have_posts() ) {
$alttext = the_title_attribute('echo=0');
$output .= '<ul>';
while ( $related_query->have_posts() ) {
$related_query->the_post();
$output .= '<li>';
$output .= '<h5 class="related-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h5>';
if( has_post_thumbnail($related_query->post->ID) ) {
$output .= '<a href="' . get_permalink() . '">' . get_the_post_thumbnail($related_query->post->ID, 'tiny-thumb', array( 'alt' => $alttext )) . '</a>';
}
$output .= '</li>';
}
$output .= '</ul>';
}
ob_get_clean();
wp_reset_postdata();
return $output;
}
Grazie!
Commenti
Mostra i restanti 2 commenti
Domande correlate
0
risposte