0

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 he did not write 'Post B', then "John" could see the sidebar when he is viewing Post A, but he could 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();

1 Answer 1

0

The reason this is not working is because you are trying to use undefined variables, they are declared outside the function and can therefor not be used without prefixing them with the global keyword.

If you have error_reporting enabled you would see warnings like this:

Notice: Undefined variable: current_user in /... on line 11

Notice: Undefined variable: author_id in /... on line 11

You enable debugging by setting WP_DEBUG to true in your wp-config.php file.

Adding the global keyword would make the variables accessible from within the function:

function showSidebarWhenNeeded()
{
  global $current_user;
  global $author_id;
  if ( $current_user->ID !== $author_id ) {
    // ...
  }
}

I would instead set the variables inside the function:

function showSidebarWhenNeeded($post_id)
{
  $author_id = get_post_field ( 'post_author', $post_id );
  $current_user = wp_get_current_user();
  if ( $current_user->ID !== $author_id ) {
    // ...
  }
}
3
  • Thank you Cyclone. That makes sense. However the code is still not working. Any ideas of how I could modify it to work?
    – orange-oc
    Sep 8, 2020 at 20:30
  • Start by turning setting WP_DEBUG to true in you wp-config.php file to get a better understanding of what is going on. Try just dumping your variables to see so they really contains the expected data e.g var_dump($post_id); var_dump($author_id); var_dump($current_user);. It is pretty hard to say anything more at this point. Sep 8, 2020 at 21:00
  • Cool, thank you.
    – orange-oc
    Sep 8, 2020 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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