WordPress前端按钮实现文章添加/移除Featured标签需求及代码求助
解决方案
1. 动态渲染按钮与表单逻辑
根据当前文章是否已标记「Featured」标签,自动切换按钮文本和操作类型,确保交互逻辑直观:
<?php // 检查当前文章是否已添加Featured标签 $is_featured = has_tag('featured', get_the_ID()); ?> <form name="front_end_featured" id="FeaturedTag" method="POST" action="<?php echo get_permalink(get_the_ID()); ?>" > <fieldset> <?php wp_nonce_field('featured_tag_nonce', 'featured_tag_nonce_field'); ?> <input type="hidden" name="featured_action" value="<?php echo $is_featured ? 'remove' : 'add'; ?>" /> <button class="button" id="featured" type="submit"> <?php echo $is_featured ? __('Unmark as Featured', 'framework') : __('Mark as Featured', 'framework'); ?> </button> </fieldset> </form>
2. 处理表单提交逻辑
在主题functions.php或当前模板文件中添加以下代码,完成标签的添加/移除操作,同时保证请求安全:
<?php if (is_user_logged_in() && isset($_POST['featured_action']) && wp_verify_nonce($_POST['featured_tag_nonce_field'], 'featured_tag_nonce')) { $post_id = get_the_ID(); $action = $_POST['featured_action']; if ($action === 'add') { // 追加Featured标签(第三个参数true表示不覆盖现有标签) wp_set_post_tags($post_id, 'featured', true); } elseif ($action === 'remove') { // 获取当前所有标签,过滤掉Featured后重新设置 $current_tags = wp_get_post_tags($post_id, array('fields' => 'names')); $updated_tags = array_diff($current_tags, ['featured']); wp_set_post_tags($post_id, $updated_tags); } // 重定向回当前文章,避免表单重复提交 wp_redirect(get_permalink($post_id)); exit; } ?>
核心优化说明
- 动态交互:自动识别文章标签状态,切换按钮显示文本和操作指令
- 避免跳转混乱:表单提交后重定向回当前文章页面,而非默认的dashboard
- 安全加固:通过nonce验证确保请求合法性,同时检查用户登录状态
- 完整移除逻辑:通过过滤现有标签列表,精准移除「Featured」标签,保留其他标签不受影响
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

