如何让指定id的HTML元素仅对登录的WordPress作者可见
实现指定元素仅对对应内容作者可见的可行方案
方案1:服务端直接控制元素输出(推荐,安全性最高)
直接在元素输出的位置加WordPress原生权限判断,无权限用户不会收到该元素的任何代码,不存在前端泄露风险。
判断逻辑需同时满足两个条件:用户已登录、当前登录用户ID等于当前访问内容的作者ID。
如果是在主题模板文件中直接输出该元素,代码示例如下:
<?php // 获取当前访问内容的作者ID $post_author_id = get_post_field( 'post_author', get_queried_object_id() ); // 权限校验通过才输出元素 if ( is_user_logged_in() && get_current_user_id() == $post_author_id ) : ?> <a id="listing_tab_documents_toggle" data-section-id="documents" class="listing-tab-toggle toggle-tab-type-custom" data-options="{}"> <!-- 元素内部内容 --> </a> <?php endif; ?>
如果该元素是后台菜单功能生成的菜单项,可通过钩子过滤菜单输出,先在「后台-外观-菜单」的目标菜单项高级设置中添加自定义CSS类author-only-item,再将以下代码添加到主题functions.php文件或自定义插件中:
add_filter( 'wp_nav_menu_objects', 'restrict_author_specific_menu_item', 10, 2 ); function restrict_author_specific_menu_item( $items, $args ) { $post_author_id = get_post_field( 'post_author', get_queried_object_id() ); foreach ( $items as $key => $item ) { // 匹配标记了专属类的目标菜单项 if ( in_array( 'author-only-item', $item->classes ) ) { // 无权限则移除该菜单项 if ( !is_user_logged_in() || get_current_user_id() != $post_author_id ) { unset( $items[$key] ); } } } return $items; }
方案2:动态输出CSS隐藏元素(适合无法直接修改输出逻辑的场景)
如果不方便改动元素的输出代码,可在页面头部动态插入CSS规则,对无权限用户隐藏该元素。将以下代码添加到主题functions.php文件即可:
add_action( 'wp_head', 'hide_author_element_for_unauthorized_users' ); function hide_author_element_for_unauthorized_users() { $post_author_id = get_post_field( 'post_author', get_queried_object_id() ); if ( !is_user_logged_in() || get_current_user_id() != $post_author_id ) { echo '<style>#listing_tab_documents_toggle { display: none !important; }</style>'; } }
注意:该方案仅为前端视觉隐藏,无权限用户仍可通过浏览器开发者工具查看到元素代码,安全性低于方案1
方案3:JavaScript动态移除元素(适合前端异步渲染的场景)
如果该元素是前端异步加载渲染的,可先通过服务端将权限判断结果传给前端JS,再动态处理元素。
首先在主题functions.php中添加代码,把权限校验结果注入到前端全局变量:
add_action( 'wp_enqueue_scripts', 'pass_author_permission_to_frontend' ); function pass_author_permission_to_frontend() { $post_author_id = get_post_field( 'post_author', get_queried_object_id() ); $is_content_author = is_user_logged_in() && get_current_user_id() == $post_author_id; wp_localize_script( 'jquery', 'wp_permission_data', array( 'is_target_author' => $is_content_author ) ); }
再添加对应的JS代码:
jQuery(document).ready(function($) { // 无权限则直接移除目标元素 if ( !wp_permission_data.is_target_author ) { $('#listing_tab_documents_toggle').remove(); } });
内容的提问来源于stack exchange,提问作者Christoph Messing
相关产品推荐
相关产品推荐

