WordPress.org

Support

Support » How-To and Troubleshooting » Passing variable to post__in not working?

Passing variable to post__in not working?

  • Hey Guys,
    I’m using a meta box to store a bunch of page ID. When I try to pass the page ID’s to the post__in parameter of WP_Query it only seems to take the first ID, not all of them.

    So, say the “relatedpages” meta box contains: 55, 33, 22

    $relatedpages = get_post_meta($post->ID, 'relatedpages', true);
    
    $args = array(
    	'post_type' 		=> 'page',
    	'posts_per_page' 	=> -1,
    	'order'			=> 'ASC',
    	'orderby' 		=> 'menu_order',
    	'post__in' 		=> array($relatedpages)
    	);
    
    $myposts = get_posts($args);
    echo $myposts;

    If you do that, you’ll only get one post. Where as if you replace ‘array($relatedpages)’ with ‘array(55, 33, 22)’ you’ll get all 3 posts.

    Is it something I’m doing wrong with my PHP syntax?

    Thanks,
    Drew

Viewing 3 replies - 1 through 3 (of 3 total)
  • So I figured out that the problem is that $relatedpages is a string, and it needs to be a comma separated integers.

    Any ideas on how to over come this?

    Thanks!

    Michael

    @alchymyth

    Forum Moderator

    try and use the php function explode()
    http://php.net/manual/en/function.explode.php

    from:
    $relatedpages = get_post_meta($post->ID, 'relatedpages', true);
    to:

    $relatedpages = get_post_meta($post->ID, 'relatedpages', true);
    $relatedpages = explode(',', $relatedpages);

    and, from:
    'post__in' => array($relatedpages)
    to:
    'post__in' => $relatedpages

    (untested)

    Hey alchymyth,
    Thanks for the help, but in the end I think the problem was the ‘post__in’ parameter can’t be used in get_posts like I wanted. Strange enough, the old ‘include’ does. So this worked!

    $args = array(
    	'post_type' 			=> 'page',
    	'posts_per_page' 		=> -1,
    	'order'				=> 'ASC',
    	'orderby' 			=> 'menu_order',
    	'include' 			=> $relatedpages
    	);
    
    $myposts = get_posts($args);

    Thanks anyway!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Passing variable to post__in not working?’ is closed to new replies.
Skip to toolbar