• I am trying to show the sidebar only if the user viewing the post is the author of that post. So anyone else viewing the post, if they are not the author, then they cannot see the sidebar.

    So if “John” wrote ‘Post A’ but “John” did not write ‘Post B’, then “John” can see the sidebar when he is viewing Post A, but he can not see it when viewing ‘Post B’.

    I have tried many variations of this but nothing seems to do the trick. Either the sidebar disappears for everyone, including the author, or it is visible to everyone.

    Also, I am using a custom post type that I made called ‘campaign’, not sure if that is why this isn’t working.

    	$author_id = get_post_field ('post_author', $post_id);
    	$current_user = wp_get_current_user();
    
    function showSidebarWhenNeeded()
    {
    	
    if ( $current_user->ID !== $author_id ) {
    	
    echo '<style>.widget-area{ display: none !important;}</style>';
    	
    }
    }
    showSidebarWhenNeeded();
Viewing 4 replies - 1 through 4 (of 4 total)
  • yes you can do that. here is the solution: display specific sidebar for each role

    thanks,
    devecity

    Thread Starter pnem

    (@pnem)

    I am not trying to display specific sidebar for each role, I am trying to display the sidebar if the user it the author of the post being viewed.

    Thanks,

    AddWeb Solution

    (@addweb-solution-pvt-ltd)

    Please add below-mentioned code in your current theme’s function.php file to hide the sidebar from the custom post type page.

    add_action('wp_footer', 'hide_widget', 100);
    
    function hide_widget() {
    	global $post;
    	if( 'campaign' == $post->post_type && is_singular() && ($post->post_author != get_current_user_id())) {
    		echo "<style>.widget-area{ display: none !important;}</style>";
    	}
    }
    Thread Starter pnem

    (@pnem)

    Thanks for the reply. I eventually got it working by removing get_sidebar(); from single.php in the child theme, and then adding this to functions.php in the child theme:

    
    function showSidebarWhenNeeded()
    {  	
    	global $post;
    	$page_id = get_queried_object_id();
    	$user_id = get_current_user_id();   
    	$author_id = get_post_field( 'post_author', $page_id );
    	
    	if ( $user_id == $author_id ) {
    	
    			get_sidebar();
    			echo '<style>.site-main{ margin-right: 0 !important;}</style>';
    
    	}
    }
    add_action( 'get_footer', 'showSidebarWhenNeeded' );
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Showing sidebar only to author of post’ is closed to new replies.