限制类别的访问和显示

时间:2012-11-14 作者:user838437

是否可以选择仅显示给已登录成员的特定类别?

我试图找到一个插件或PHP解决方案,但找不到任何仍然相关的东西。

2 个回复
最合适的回答,由SO网友:Stephen Harris 整理而成

是:)。

以下内容将影响前端对帖子的所有查询,包括“二次循环”(例如侧面的帖子列表),但不会影响自定义帖子类型。所以这可能不是你想要的,但原则是一样的:

add_action(\'pre_get_posts\',\'wpse72569_maybe_filter_out_category\');

function wpse72569_maybe_filter_out_category( $query ){

     //Don\'t touch the admin
     if( is_admin() )
         return;

     //Leave logged in users alone
     if( is_user_logged_in() )
         return;

     //Only effect \'post\' queries
     $post_types = $query->get(\'post_type\');
     if( !empty($post_types) && \'post\' != $post_types )
         return;

     //Get current tax query
     $tax_query = $query->get(\'tax_query\');

     //Return only posts which are not in category with ID 1
     $tax_query[] = array(
        \'taxonomy\' => \'category\',
        \'field\' => \'id\',
        \'terms\' => array( 1 ),
        \'operator\' => \'NOT IN\'
          );

     //If this is \'OR\', then our tax query above might be ignored.
     $tax_query[\'relation\'] = \'AND\';

     $query->set(\'tax_query\',$tax_query);

}

SO网友:Nicole

如果希望将其用作循环类型结构,可以尝试以下操作:

<?php
  if ( is_user_logged_in() ) {

     //Only displays if the user is logged in.

     query_posts(\'cat=1\'); // Replace the category number with the correct category number you want to display
      while (have_posts()) : the_post();
      the_content();
     endwhile;

 } else {

     // Everyone else that is not logged in

     query_posts(\'cat=2\'); // Replace the category number with the correct category number you want to display
       while (have_posts()) : the_post();
       the_content();
    endwhile;

}
?> 
If 您希望只显示指向类别页面的链接,就像显示菜单一样。您可以执行以下操作:

使用WP nav菜单功能。在中注册菜单functions.php在主题文件夹中。您可以通过将以下内容添加到文件中来完成此操作:

<?php

  register_nav_menus( array(
     \'primary\' => __( \'Primary Navigation\', \'your_theme_name\' ), // Your main navigation. Replace "your_theme_name" with the theme you are using.
     \'logged_in_user\' => __( \'Logged In User\', \'your_theme_name\' ), // Remember replace "your_theme_name" with the theme you are using.

) );
?>
通过管理将类别添加到菜单中。

在你的主题中调用它。这与我们上面所做的类似,但只是将其作为菜单列出,而不是发布列表。

<?php
   if ( is_user_logged_in() ) {

    //Only displays if the user is logged in.

     wp_nav_menu( array( \'container\' => false, \'menu_id\' => \'nav\', \'theme_location\' => \'logged_in_user\' ) );

   } else {

  // Everyone else that is not logged in
 // You can display anything you want to none logged in users or just leave it blank to display nothing.

  }
 ?> 

结束

相关推荐

plugins_url vs plugin_dir_url

我看到WordPress插件在为一些文件夹创建常量时使用plugins\\u url或plugin\\u dir\\u url。一个比另一个好吗?示例:define( \'MEMBERS_URI\', trailingslashit( plugin_dir_url( __FILE__ ) ) ); define( \'WPACCESS_INC\', plugins_url( \'inc\', __FILE__ ) , true );