Cum să afișezi articole dintr-o categorie specifică folosind o interogare personalizată în WordPress?
Salut! Vreau să afișez o categorie specifică dintr-o interogare personalizată în WordPress. Codul meu funcționează bine și obține ultimele 4 articole, dar acum vreau să preiau articole dintr-o categorie specifică. Codul meu este mai jos, mulțumesc:
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');
Și aici este codul meu complet:
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;
Acum vreau să adaug rezultatul final, vezi codul de mai jos:
" id="nav-fragment-"> "> " class="ui-tabs-panel" style=""> " alt="" /> " >" >Citește mai mult
modul recomandat este:
<?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(); // sau the_content(); pentru conținutul complet al articolului
endwhile;endif;
?>

Totul este în regulă, prima sugestie de la @Ammu a funcționat de asemenea. A trebuit să modific valorile din array pentru a se potrivi cu afirmația, iată codul:
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");

Trebuie remarcat faptul că ocolirea API-ului și interogarea directă poate avea consecințe neintenționate, elimini posibilitatea de a face toate lucrurile pe care API-ul le permite - filtre, acțiuni etc. Ar trebui să utilizați întotdeauna API-ul (WP_Query
) atunci când este posibil și nu o interogare SQL directă.
