Cómo mostrar entradas de una categoría específica usando una consulta personalizada en WordPress
Hola, quiero mostrar una categoría específica desde una consulta personalizada en WordPress. Mi código funciona bien y obtiene las últimas 4 entradas, pero ahora quiero recuperar una categoría específica. Mi código está abajo, gracias:
global $wpdb;
$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');
Y aquí está mi código completo:
global $wpdb;
$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) {
$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;
Ahora quiero agregar la salida final, ver el código abajo:
" id="nav-fragment-"> "> " class="ui-tabs-panel" style=""> " alt="" /> " >" >Leer más
la forma recomendada es:
<?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(); // o the_content(); para el contenido completo del post
endwhile;endif;
?>

Todo correcto, la primera sugerencia de @Ammu también funcionaba. Necesitaba cambiar los valores del array para que coincidieran con la declaración, aquí está el código:
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");

Debe tenerse en cuenta que omitir la API y consultar directamente puede tener consecuencias no deseadas, ya que se pierden todas las funcionalidades que la API permite, como filtros, acciones, etc. Siempre deberías usar la API (WP_Query
) cuando sea posible y no una consulta SQL directa.
