如何在WordPress中使用自定义查询显示特定类别的帖子?

时间:2014-09-30 作者:Jono

您好,我想在WordPress中显示自定义查询中的特定类别。我的代码运行良好,它获得了最新的4篇帖子,但我现在想要的是检索一个特定的类别。我的代码如下,谢谢:

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\');
这是我的完整代码:

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;
现在,我想添加最终输出pout,请参见下面的代码:

阅读更多信息

2 个回复
最合适的回答,由SO网友:Jono 整理而成

很好,@Ammu的第一个建议也起到了作用。我需要更改数组中的值以匹配语句以下是代码:

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");

SO网友:Zammuuz

建议的方式是:

    <?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(); // or the_content(); for full post content
    endwhile;endif;
?>

结束

相关推荐

PHP error in shortcode

有人能帮我看看这段代码中的错误吗?我正试图通过我发现的短代码实现一个函数here:<?php if (function_exists(‘wooslider’)) echo do_shortcode(‘[wooslider slider_type=\"posts\" limit=\"3\" link_title=\"true\" layout=\"text-bottom\" overlay=\"full\" category=\"homepage-feature-post\"]‘); ?>&#x