show an element only to the author of the post

Ian

(@plantprogrammer)

Hi, hugomarcelo, I would use an “if” statement enclosing the code you intend to use:

if( is_user_logged_in() && get_current_user_id() == $post->post_author )
{
 //your code here
}

References:
https://codex.wordpress.org/Function_Reference/$post
https://developer.wordpress.org/reference/functions/get_current_user_id/
https://developer.wordpress.org/reference/functions/is_user_logged_in/

@plantprogrammer
Out of curiosity, is is_user_logged_in() even needed here?

@plantprogrammer

<?php
	if ( is_user_logged_in() && get_current_user_id() == $post->post_author ) { 
		<div><a href="<?php get_edit_post_link( int|WP_Post $id, string $context = 'display' ) ?>">Edit post</a></div> 
	}
?>

I’m not very experienced with code, but I put this in my single.php and my website now tells me that there is a critical error when I try to access the post. How to fix? Please help me.

You cannot nest <?php ?> blocks. $id may not be assigned, use get_the_ID() if there’s any doubt. You may need a global $post; line so $post->post_author works. I don’t think we need is_user_logged_in() since get_current_user_id() shouldn’t error for non-logged in users, it ought to return 0. You should not use type identifiers (int, string, etc.) when calling functions, instead ensure data is the correct type. Do you use $context later on? I assume no. The function call must be terminated with a ;

<?php  global $post;  //not needed if it occurs elsewhere
	if ( get_current_user_id() == $post->post_author ) { ?>
		<div><a href="<?php get_edit_post_link( get_the_ID(), 'display' ); ?>">Edit post</a></div> 
<?php	} ?>

@bcworkz Thanks! This works perfectly! I’m so happy.
You slay!



Source link