NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Display User's Liked Articles in Their Account
Intermediate
Web Hosting Canada

Last modified : Oct 01 2022

Estimated reading time : 1 minute, 58 seconds - 206 words

With this tutorial, we will show you how to display the articles liked by a user in their account. We need to create a query that will display the posts with the post meta “like” and its value are equal to the WordPress user’s ID.

Obviously, to be make this function works, we need a Like system so users can like posts such as this one: WordPress Post Like System

You also need a user account and do not forget the conditions in the user’s profile page.

<?php 
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly 
if ( is_user_logged_in()) : 
global $current_user; 
wp_get_current_user();
$user = $current_user->ID; 
?>

Display posts liked by the user

In their user account, we will display the list of recently liked post. This create this query, we fist need to fetch the user’s ID with get_current_user_id() via WordPress’ get_currentuserinfo(). Next, the $types variable with fetch the required Post Type (In our example it’s Listings. Simply replace it by your Post Type or article post). We will display 10 and then we’ll run a meta_query that will match the author’s ID and the post meta key.

Now we will loop. We implement an incremented ranking with $i. Here’s our query:
(The user_liked key must be changed by your post meta key representing the Like)

<?php
	$author_id = get_current_user_id();
	$types = 'listings';
	$args = array(
	  'numberposts' => '10',
	  'post_type' => $types,
	  'meta_query' => array (
		array (
		  'key' => '_user_liked',
		  'value' => $author_id,
		  'compare' => 'LIKE'
		)
	  ) ); 
	$like_query = new WP_Query( $args );
	if ( $like_query->have_posts() ) :	?>
	<ul class="user-likes">
		<?php $i = 1; while ( $like_query->have_posts() ) : $like_query->the_post(); ?>
			 <li>
				 <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
				 <?php echo $i; ?> <?php _e('-'); ?>
				 <?php the_title(); ?>
				</a>
			</li>
		<?php $i++; endwhile; ?>
	</ul>
	<?php else : ?>
	<p><?php _e( 'Pas de J&#39;aime', 'via-entreprises' ); ?></p>
	<?php 
	endif; 
	wp_reset_postdata(); 
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>