Freddy
Freddy

Reputation: 867

Run wp_query based on IDs found in array

I have a session array ($_SESSION['recently_viewed']) which currently outputs the following:

array(3) { [0]=> int(635) [1]=> int(643) [2]=> int(474) }

635, 643 and 474 are the IDs of posts in my custom post type called accessories.

I'm trying to display posts that are part of this array, but unsure how to do this logically.

So far I have:

<?php
global $post;

$args = array(
  'post_type' => 'accessories',
  'p' => $_SESSION['recently_viewed'], // something like this, but logically correct
  'post_status' => 'publish',
);

$query = new WP_Query( $args );

if($query->have_posts() ) :
  while ( $query->have_posts() ) : $query->the_post();
    echo the_title();
  endwhile; wp_reset_postdata(); ?>
<?php endif; ?>

How do I go about this?

Upvotes: 0

Views: 23

Answers (1)

iismaell
iismaell

Reputation: 633

You can pass in the the resulting array in the post__in parameter of the WP_Query.

$args = array(
  'post_type' => 'accessories',
  'post__in' => $_SESSION['recently_viewed'], 
  'post_status' => 'publish',
);

But you may need to restructure the $_SESSION['recently_viewed'] and make sure that it is a valid array. If it is valid already, then the query above should work without problem.

More info in the documentation.

// https://developer.wordpress.org/reference/classes/wp_query/#post-page-parameters

Upvotes: 1

Related Questions