In this tutorial we're going to build a WordPress shortcode that will allow us to only show the posts of the logged in user. This is useful if you have a website which allows authors to post their own content and you need a page to display all the posts for that author. The reason why we're using a shortcode for this is so that we can keep the styling consistent with the other pages. There's a few stages to this shortcode, first you need to create a plugin to store the shortcode, then check if the user is logged in, if the user is logged in then search for posts searched by the logged in user.
Create A WordPress Shortcode
To create a WordPress shortcode you need to use the function add_shortcode(), the first parameter is the shortcode name and the second is the function to run on calling the shortcode.
add_shortcode('display_own_posts', array($this, 'display_own_posts'));
You'll notice that the second parameter is an array, this is because we're building the shortcode using PHP OOP so we need to send in the class and function to run for the callback function. ## Get Own Authored Posts
First we need to check if the user is logged in, if they're not then we want to return nothing. Shortcodes work by displaying whatever is returned from the shortcode function.
if(!is_user_logged_in())
{
return '';
}
Then we need to get all the posts that are authored by the logged in user. We use the parameters post_per_page
and author
in the WP_Query class to get all the posts.
$query = new WP_Query([
'post_per_page' => -1,
'author' => get_current_user_id()
]);
Display The Posts
Because we're using a shortcode we need to make sure that all the content to display the posts is returned from the function and not just echo'd by the function. To do this we use PHP output buffer to collect the content in a variable.
ob_start();
// Display the content here
$html = ob_get_contents();
ob_end_clean();
return $html;
As we want to keep the same styling as the theme we can use the theme part functions to get the theme files get_template_part().
get_template_part( 'content', 'single' );
Now we just to need to loop through the posts and display them using the get_template_part()
function. This will then
output all the author posts with the same styling as the theme.
if($query->have_posts())
{
ob_start();
while ( $query->have_posts() )
{
$query->the_post();
get_template_part( 'content', 'single' );
}
$html = ob_get_contents();
ob_end_clean();
return $html;
}