Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

In my functions.php I require PHP files which register custom post types, if I'm logged in as an admin.

if (is_admin())
    require_once(TEMPLATEPATH . '/custom-post-types/cpt.php');

This works great, except that the wrong template is loaded. Instead of single-{cpt}.php the index.php is used. If I remove if (is_admin()) everything works correct, but of course the custom post type becomes visible for every non-admin.

How can I solve that?

share|improve this question
    
See @s_ha_dum's answer regarding your misunderstanding of the is_admin() conditional. But for answering the underlying question, I have one of my own: what is the purpose of only registering CPTs when the current user is an Administrator? What are you trying to accomplish with that? I think there may be a better way to accomplish whatever it is you're trying to do, but we need to have a better idea of what the ultimate objective is. –  Chip Bennett Jan 3 '13 at 15:29
    
I wanted to check my CPT template on the live machine and deny access to the template and CPT for non-admins. –  Pipo Jan 4 '13 at 10:31
add comment

1 Answer 1

If you don't register the CPT then index.php will be used, and if you only register the CPT for the backend, which is what is_admin checks for, then index.php will pretty much always be used.

In other words, you are only registering your CPT for the backend, not for the front. It isn't ever going to work correctly that way.

What you are doing wrong is fundamentally misunderstanding the is_admin function.

I think what you need is current_user_can but you wouldn't want to register the post type on that switch, or I don't think you do. That will probably cause unwanted behavior as well, but of course you are welcome to try. Maybe something like...

function hide_cpt($content) {
  global $post; // might not be necessary
  if ('your-post-type-name' == $post->post_type && current_user_can('administrator')) {
   return 'You can\'t look at this';
  }
  return $content;
}
add_filter('the_content','hide_cpt');

It is hard to say for sure if that will do what you want though. Your description isn't heavy on detail.

share|improve this answer
    
Sorry that I can't upvote you, but you are completely right. I misunderstood is_admin, because I thought it means user is admin and not user is in backend. –  Pipo Jan 4 '13 at 10:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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