Skip to content

Instantly share code, notes, and snippets.

@kylephillips
Last active October 14, 2022 19:33
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylephillips/9fe12f195c671c989af3 to your computer and use it in GitHub Desktop.
Save kylephillips/9fe12f195c671c989af3 to your computer and use it in GitHub Desktop.
Using the Favorites get_user_favorites() function to display favorited post data in a custom format
<?php
// Method 1: simple foreach loop
$favorites = get_user_favorites();
if ( isset($favorites) && !empty($favorites) ) :
foreach ( $favorites as $favorite ) :
// You'll have access to the post ID in this foreach loop, so you can use WP functions like get_the_title($favorite);
endforeach;
endif;
/**
* Method 2: WP_Query Object
* Check if there are favorites before instantiating the WP_Query.
* Passing an empty array as an argument returns ALL posts.
* @see https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
*/
$favorites = get_user_favorites();
if ( $favorites ) : // This is important: if an empty array is passed into the WP_Query parameters, all posts will be returned
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; // If you want to include pagination
$favorites_query = new WP_Query(array(
'post_type' => 'post', // If you have multiple post types, pass an array
'posts_per_page' => -1,
'ignore_sticky_posts' => true,
'post__in' => $favorites,
'paged' => $paged // If you want to include pagination, and have a specific posts_per_page set
));
if ( $favorites_query->have_posts() ) : while ( $favorites_query->have_posts() ) : $favorites_query->the_post();
// Treat this like any other WP loop
endwhile;
next_posts_link( 'Older Favorites', $favorites_query->max_num_pages );
previous_posts_link( 'Newer Favorites' );
endif; wp_reset_postdata();
else :
// No Favorites
endif;
@catmatteson
Copy link

This is awesome thank you!

@sarfaraz72
Copy link

For those who wants to avoid loop from repeating in category template use

if ( $favorites_query->have_posts() ) : $favorites_query->the_post(); and remove endwhile;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment