Search code examples
phpwordpress

Wordpress query - if less than 3 posts, randomly pick posts


I have a query, which returns posts with custom field "featured". The code looks

<?php
$args = array( 
    'post_type' => 'koncert', 
    'posts_per_page' => 3, 
    'meta_query' => array(
        array(
            'key' => 'featured', // name of custom field
            'value' => '1', 
            'compare' => 'LIKE'
        ),
    ), 
    'meta_key' => 'datum', 
    'orderby' => 'meta_value', 
    'order' => ASC
);

$loop = new WP_Query( $args );
$countposts = $loop->post_count;
$count = 1;
// START OF THE LOOP
while ( $loop->have_posts() ) : $loop->the_post();
    /* do something */
    $count++;
endwhile;
wp_reset_postdata();
?>

The problem is I need the query to always return at least three 'featured' posts, which is not always the case.

So, what would be the easiest way to check the posts count in the query, and if less than three, randomly choose another post(s) from this custom post type (and still have the query sorted by 'meta_key' => 'datum'?

Thanks for help


Solution

  • Second option is to use a SQL query to fetch this information instead of the built in WordPress functions. Gets all the posts for 'koncert' type that are published, then joins the post meta table twice and sorts based on the meta values for the different gets, using LIMIT to return only 3 results.

    global $wpdb;
    $sql = <<<SQL
        SELECT p.ID, p.post_content, p.post_title, datum.meta_value as datum, featured.meta_value as featured
        FROM {$wpdb->posts} p
        LEFT JOIN {$wpdb->postmeta} featured 
            ON featured.post_id = p.ID 
            AND featured.meta_key = 'featured'
        LEFT JOIN {$wpdb->postmeta} datum 
            ON datum.post_id = p.ID 
            AND datum.meta_key = 'datum'
        WHERE 
            p.post_type = 'koncert' 
            AND p.post_status = 'publish'
        ORDER BY featured DESC, datum DESC, RAND()
        LIMIT 3
    SQL;
    $posts = $wpdb->get_results( $sql );