Support » Plugins and Hacks » Using multiple instances of get_posts to pull posts with different meta values

  • I find that get_posts is somewhat limited in how it deals with meta data. Here is a code fragment demonstrating how you can combine and sort different get_posts arrays.

    $postset1 = get_posts('numberposts=3&meta_key=Label&meta_value=Value1&category=10');
    	$postset2 = get_posts('numberposts=3&meta_key=Label&meta_value=Value2&category=10');
    	$postset3 = get_posts('numberposts=3&meta_key=Label&meta_value=Value3&category=10');
    	$postsetx = array_merge($postset1, $postset2, $postset3);
    	foreach($postsetx as $set)
    		$setsort[] = $set->post_date;
    
    	array_multisort($setsort, SORT_DESC, $postsetx);
    
    	foreach ($postsetx AS $post): setup_postdata($post); if ($posted) { if (strtotime($post->post_date) < strtotime('-2 months')) { break; } }
    
    (Loop goes here.)

    This code pulls 3 recent posts from category 10 features Value1, Value2, and Value3 as meta values. The separate arrays are then merged and sorted by post date. Finally, the loop is cancelled if the posts are older than 2 months.

    It isn’t terribly efficient to do it this way but until meta_value takes more than one option this is a functional workaround.

  • The topic ‘Using multiple instances of get_posts to pull posts with different meta values’ is closed to new replies.