Support

Account

Home Forums General Issues Select posts for loop based on whether an array contains value or not

Helping

Select posts for loop based on whether an array contains value or not

  • Hi, I’ve got a couple of custom posts that all contain the custom field ‘assigned_page’, which is an array of strings containing page id’s. I want to run a loop and select the posts that have the current page ID in their custom array. I can’t get it to work properly, I wonder what I’m doing wrong. Here’s my code:

    
    	// Get the current page ID
    	global $post;
    	$current_page = $post->ID;
    	$int = (int)$current_page;
    	$string_page = (string)$current_page;
    	$current_parent_page = $mv_is_subpage->ID;
    	
    	// Post selection
    	
    	$args = array (
    		'post_type'      => $post_type,
    		'posts_per_page' => $posts_per_page,
    		'orderby'        => $orderby, 
    		'order'          => $order,
    		'no_found_rows'  => 1,
    //		'category_name' => 'test'
    		'meta_query' => array( 
    		array(
    					'meta_key' => 'assigned_page', 
    					'meta_value' => $string_page, 
    					)
    				),
    		);
    

    Then I just run the loop, but it’s actually returning all posts. What am I doing wrong?

    Thanks all in advance

  • Hi,

    Try this:

    
    global $post;
    	$current_page = $post->ID;
    	$int = (int)$current_page;
    	$string_page = (string)$current_page;
    	$current_parent_page = $mv_is_subpage->ID;
    	
    	// Post selection
    	
    	$args = array (
    		'post_type'      => $post_type,
    		'posts_per_page' => $posts_per_page,
    		'orderby'        => $orderby, 
    		'order'          => $order,
    		'no_found_rows'  => 1,
    //		'category_name' => 'test'
    		'meta_query' => array( 
    			array(
    				'key' => 'assigned_page', 
    				'value' => "$string_page",
    				'compare' => 'LIKE' 
    			)
    		),
    	);
    

    Also you have some strange parameters such as “no_found_rows” and “category_name” which does not exist in the wp_query class.. These should probably be removed if you dont know what you’re doing with them.. And make sure that your variables such as $order etc. is set!

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Select posts for loop based on whether an array contains value or not’ is closed to new replies.