post__in - Placing content from a foreach loop inside of an array

I know this code is incorrect, but it's a basis of what I am trying to achieve.

I am parsing an xml feed via PHP and running a foreach loop to get a value from a specific key.

Here is the snippet I am using:

$feed = file_get_contents("https://www.feedurl.com/xml"); // Feed URL
$xml = new SimpleXmlElement($feed);

$output = array();
foreach($xml-entry as $entry){
  $attributes = $entry-id-attributes(URI_RSS);
  $im = $entry-children(URI_RSS);                                    

  // Get item's ID
  $id = $entry-id;
  $attr = $id-attributes('im', TRUE);

  $output[] = $attr['id'];
}

$testarray = "'" . implode("', '", $output) . "'"; // Place the 'output' from the foreach into this formation: 'xxx','xxx','xxx',etc    
$lastarray = array($testarray);

$args = array(
  'post_type' = $post_type,
  'post__in'      = $lastarray
);

$wp_query = new WP_Query( $args );

When I echo '$testarray' it displays correctly in the way I had set it up: 'xxx','xxx','xxx',etc

However, trying to place '$testarray' as an array for 'post__in' doesn't work. I know for sure my code isn't set correctly and am not sure how I would do it.

The 'post__in' would be paginated, loading via a infinite loop.

Thanks! Joe.

Topic wp-parse-args parse array loop php Wordpress

Category Web


Update to know that I was able to accomplish this by this snippet below:

For reference:

$jsonfeed = file_get_contents('http://www.jsonfeed.com');
$results = json_decode($top100, true);

foreach($results['feed']['entry'] as $post){ // This is custom for my json
  $post_ids[] = $entry['id']['attributes']['second_id'];
}

var_dump($post_ids); // dump array

$args = array(
  'post_type' => $post_type,
  'post__in'  => $post_ids,
  'ignore_sticky_posts' => 1,
);

$wp_query = new WP_Query( $args );

if (have_posts()) :
   usort($wp_query->posts, function($a, $b) use ($post_ids) { // Lists loop in order of the array -> http://pastebin.com/3vwiDSfb
      return array_search($a->ID, $post_ids) - array_search($b->ID, $post_ids);
   });
   while(have_posts()) : the_post();
   endwhile;    
endif;

Thanks for all that helped.


Looking at your code - $lastarray will not be an array of ID's (as you might be expecting), but an array with a single element containing a string of comma separated IDs.

$output is already an array of the $attr['id'] - try commenting (add // to the start) to the lines starting with $testarray and $lastarray and replacing 'post__in' => $lastarray with 'post__in' => $output

See if that helps.

Edit: to clarify - post__in expects an array (rather than 'id','id','id' string) - see here

Jon

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.