WordPress.org

Ready to get started?Download WordPress

Forums

Passing variable to post__in not working? (4 posts)

  1. Drew Baker
    Member
    Posted 3 years ago #

    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

  2. Drew Baker
    Member
    Posted 3 years ago #

    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!

  3. alchymyth
    Forum Moderator
    Posted 3 years ago #

    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)

  4. Drew Baker
    Member
    Posted 3 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic