I'd like to grab a random post but only one which has a post excerpt. Is there any way that I can query this during a call to get_posts() or wp_query()?

Bonus points if I could do it with REST, I explored down that route and found myself back at get_posts().

2 Answers 2


Something along these lines should work, not tested for syntax errors though

        function random_post() { 

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

        $post = query_posts( $args );



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

the following code will check whether there is a record excerpt:

if ( has_excerpt( $post->ID ) ) {
    // This post has excerpt
} else {
    // This post has no excerpt

The following code will return 1 record in which there excerpt:

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;  

call function:

$post_id = get_random_post_by_excerpt('post');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.