仅返回具有POST_EXCEPT的帖子

时间:2017-02-15 作者:Kevin Nugent

我想随便找一篇文章,但只有一篇有文章摘录的。有什么方法可以在调用get_posts()wp_query()?

如果我能休息一下,我会得到额外的积分,我沿着这条路线探索,发现自己回到了get_posts().

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

虽然没有测试语法错误,但应该可以做到这一点

        function random_post() { 

        $args = array(
            \'post_type\' => \'post\',
            \'orderby\'   => \'rand\',
            \'posts_per_page\' => 1, 
            );

        $post = query_posts( $args );

        }

        if(!$post->post_excerpt){
          random_post();
        }

// Then down here you would do whatever with the $post object

SO网友:TrubinE

以下代码将检查是否有记录摘录:

if ( has_excerpt( $post->ID ) ) {
    // This post has excerpt
} else {
    // This post has no excerpt
}
以下代码将返回1条包含摘录的记录:

function get_random_post_by_excerpt($post_type){
global $wpdb;
$id_post = $wpdb->get_var($wpdb->prepare("SELECT $wpdb->posts.ID FROM $wpdb->posts WHERE $wpdb->posts.post_type = \'%s\' AND $wpdb->posts.post_status = \'publish\' AND $wpdb->posts.post_excerpt != \'\' ORDER BY RAND();", $post_type));

return $id_post = (!empty($id_post))?$id_post:false;  
}
调用函数:

$post_id = get_random_post_by_excerpt(\'post\');