获取wpdb中特定类别的所有帖子

时间:2018-06-25 作者:Godwin Alex Ogbonda

拜托,我有点沮丧。我正在尝试从wpdb获取所有来自特定类别id的帖子,下面是我的代码。我不知道我哪里弄错了。

global $wpdb;
$posts = $wpdb->get_results( "SELECT ID, post_title, post_modified_gmt
    FROM $wpdb->posts
    LEFT JOIN  $wpdb->term_relationships  as t
        ON ID = t.object_id
    WHERE post_type = \'post\' AND post_status = \'publish\' AND t.term_taxonomy_id = 3
    WHERE post_status = \'publish\'
    AND post_password = \'\'
    AND post_type = \'post\'
    ORDER BY post_type DESC, post_modified DESC
    LIMIT 10"
);

1 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

嗯,您的代码有很多地方不完全正确:

$posts = $wpdb->get_results( "SELECT ID, post_title, post_modified_gmt
    FROM $wpdb->posts
    LEFT JOIN  $wpdb->term_relationships  as t
        ON ID = t.object_id
    WHERE post_type = \'post\' AND post_status = \'publish\' AND t.term_taxonomy_id = 3
    WHERE post_status = \'publish\'  # <-- !! second WHERE clause
    AND post_password = \'\'
    AND post_type = \'post\'  # <-- !! you\'ve already used this condition
    ORDER BY post_type DESC, post_modified DESC  # <-- !! why do you order by post_type if you select only posts??
    LIMIT 10"
);
那么如何更好地书写呢
global $wpdb;
$posts = $wpdb->get_results( $wpdb->prepare(
    "SELECT p.ID, p.post_title, p.post_modified_gmt
     FROM {$wpdb->posts} as p
        INNER JOIN {$wpdb->term_relationships} as t  # <-- you can use INNER JOIN in here, since you want posts from category, so every post has to have some term assigned to it
        ON (p.ID = t.object_id)
     WHERE p.post_type = \'post\' AND p.post_status = \'publish\' AND p.post_password = \'\' AND t.term_taxonomy_id = %d
     ORDER BY p.post_modified_gmt DESC
     LIMIT 10",
     3  // <-- Notice: you\'ll have to use term_taxonomy_id and not term_id in here
));

结束

相关推荐

无法使用$wpdb方法查询自定义表

我使用Sequel Pro为我的Wordpress站点创建了一个自定义表。然后,我尝试使用$wpdb方法从Wordpress PHP文件中查询表。虽然我能够使用标准Wordpress表成功运行查询,但它不适用于我创建的自定义表。所以这一个有效:<?php global $wpdb; $result = $wpdb->get_results ( \" SELECT * FROM $wpdb->users