最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Show current user posts only

programmeradmin5浏览0评论

I am trying to show the front end user only the posts they created. example/all-releases

Like User-1 can only see his posts, not the User-2 posts nor admin posts.

I tried various function codes from the previous question but the latest WordPress version does not support any.

Let me tell you the situation: The user is a Logged In user. The posts are created by Gravity Forms.

I am trying to show the front end user only the posts they created. example.com/all-releases

Like User-1 can only see his posts, not the User-2 posts nor admin posts.

I tried various function codes from the previous question but the latest WordPress version does not support any.

Let me tell you the situation: The user is a Logged In user. The posts are created by Gravity Forms.

Share Improve this question edited Sep 28, 2019 at 13:43 Chetan Vaghela 2,3984 gold badges10 silver badges16 bronze badges asked Sep 27, 2019 at 23:21 AmanAman 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1
<?php
    $query = new WP_Query([
        'author' => get_current_user_id(),
    ]);

while ( $query->have_posts() ) {
    $query->the_post();
    the_title();
}
    wp_reset_postdata();
?>

In the example above we are using WP_Query look on the reference guide for additional parameters such as different post types like if you want to get only pages, posts or custom post types, as well as the number of elements to be displayed.

Also be aware of the usage of wp_reset_postdata as the example above uses $query->the_post()

Note: If you use the_post() with your query, you need to run wp_reset_postdata() afterwards to have template tags use the main query’s current post again.`

You can also break the code above to add additional HTML tags in between each like:

while( $query->have_posts() ) : $query->the_post(); 
?>
<h2><?php the_title(); ?><h2>
<div><?php the_content(); ?>
<?php endwhile; wp_reset_postdata(); ?>

The example above uses get_current_user_id which assumes there's a user logged in as it returns zero if no user is logged in you can use some logic around that to display different data in that scenario.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论