4

I need to edit the below code to only display posts for the current logged-in user/author.

It is currently within a Wordpress theme page template file and works well. Any help would be appreciated as my knowledge is limited.

$loop = new WP_Query( array( 'post_type' => 'html5-blank', 'category_name' => 'chapter' ) );
if ( $loop->have_posts() ) :
    while ( $loop->have_posts() ) : $loop->the_post(); ?>


        <div class="pindex">
            <div class="ptitle">
                <h2><?php echo get_the_title(); ?></h2>
            </div>
    <!-- post thumbnail -->

    <div class="featured-image">        <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>

        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">

            <?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?>

        </a>

    <?php endif; ?></div>

    <!-- /post thumbnail -->
                <div class="post-content">
  <?php the_content(); ?>
</div>

        </div>
    <?php endwhile;
endif;
wp_reset_postdata();

The above code is based on an answer found here: Custom Loop for Custom Post Type

1 Answer 1

3

You can get the current user ID using $user_id = get_current_user_id(); and use the $user_id in your query.

$user_id = get_current_user_id();
$loop = new WP_Query( array( 'post_type' => 'html5-blank', 'category_name' => 'chapter', 'author' => $user_id ) ); 
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>


<div class="pindex">
    <div class="ptitle">
        <h2><?php echo get_the_title(); ?></h2>
    </div>
    <!-- post thumbnail -->

    <div class="featured-image">
        <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>

        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">

            <?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?>

        </a>

        <?php endif; ?>
    </div>

    <!-- /post thumbnail -->
    <div class="post-content">
        <?php the_content(); ?>
    </div>

</div>
<?php endwhile;
endif;
wp_reset_postdata();
4
  • Thank you for your answer. I am not sure where exactly should I put $user_ID = get_current_user_id();
    – Kay
    Commented May 3, 2015 at 4:50
  • I have updated the code.
    – m4n0
    Commented May 3, 2015 at 4:53
  • Thank you. Just had to change the case of $user_ID to $user_id to match the query then it worked. Thanks again.
    – Kay
    Commented May 3, 2015 at 5:24
  • Great that it worked! Code updated.
    – m4n0
    Commented May 3, 2015 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.