Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Roberto Lozano
Roberto Lozano
1,079 Points

Wordpress - Retrieving specific posts from the current user

I have a custom post with 2 fields, the first field being the user, and the second one being a table, and whenever a user is logged in, I must display all of the posts that have the user in the 1st field, this is what I found:

In wp_user the ID of the user I'll be using to test it will have: user_id = 3

In wp_postmeta, I have a row with these values:

-post_id=92 -meta_value=3

And in wp_posts, in the ID = 92, I have the specific post name I was looking for.

I'm pretty confused on how to make this code dynamically, so any user will be able to see their own posts. And BTW, the post_author is the admin, so I can't use that field

Basiclly, I must retrieve the post_id from wp_postmeta by only using the the meta_value which I've seen a couple of guides but can't really understand how to do it. I know I must use wp_get_current_user(). Please someone explain me with detail how to achieve this.

Thanks

2 Answers

If you're using user IDs as the values in your custom fields, this should work. With a little tweaking, it could work with usernames and emails as well.

<?php

$userID;
if ( wp_get_current_user() instanceof WP_User ) {
    $userID = wp_get_current_user()->ID;
}

$users_query = new WP_Query( array(
    'post_type' => 'your_custom_post_type',
    'meta_key' => 'slug_of_custom_field',
    'meta_value' => $userID,
) );

?>

<?php if ( $users_query->have_posts() ): ?>

    <?php while ( $users_query->have_posts(): $users_query->the_post() ) ?>

        <!-- HTML here -->

    <?php endwhile; ?>

<?php endif; ?>
Kevin Korte
Kevin Korte
28,149 Points

Before I can help, I have a few questions.

1) So every post was added by the admin? Are these users tagged? Or are the users the author, but only the admin has the ability to publish the post?

2) Is the user given the option to choose which other use they want to see posts from, or are they only allowed to see "their" posts?

3) What's the goal with the table custom field? Should the posts generate into it?

4) What data are you entering into the table if at all? I'm a bit confused why there is a custom post type with a user field and a table? Did you use any plugins to create these custom post types and custom fields?