You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章类型开关关闭时如何实现文章重定向

WordPress自定义文章类型单篇访问开关实现方案

整个实现分4个部分,代码可直接加到主题functions.php或自定义功能插件中使用。

1. 优化作者页文章列表,绑定独立切换开关

首先替换你原有作者页的文章查询代码,去掉重复的WP_Query实例,每篇文章输出对应开关,读取当前存储的公开访问状态:

global $current_user;
wp_get_current_user(); // 原代码中get_currentuserinfo已废弃,替换为官方推荐函数
$authorID = $current_user->ID;
$args = array(
    'post_type' => 'petcontact',
    'posts_per_page' => -1,
    'author' => $authorID,
    'post_status' => 'publish' // 仅查询已发布文章
);

if($current_user){
    $loop = new WP_Query( $args ); 
    while ( $loop->have_posts() ) : $loop->the_post(); 
        $post_id = get_the_ID();
        // 读取当前访问状态,默认值1为公开可访问,0为关闭跳转
        $is_public = get_post_meta($post_id, '_petcontact_public_access', true) ?: 1;
        ?>
        <div class="petcontact-item">
            <h3><?php the_title(); ?></h3>
            <label class="access-switch">
                <input type="checkbox" class="access-toggle" data-postid="<?php echo esc_attr($post_id); ?>" <?php checked($is_public, 1); ?>>
                <span class="switch-label"><?php echo $is_public ? '公开访问已开启' : '公开访问已关闭'; ?></span>
            </label>
        </div>
        <?php
    endwhile;
    wp_reset_postdata(); 
}

可自行添加CSS美化开关样式,不影响核心功能运行。

2. 注册AJAX接口处理状态更新

在functions.php中添加后端处理逻辑,必须做权限校验,防止越权修改他人文章:

// 注册登录用户可触发的AJAX动作
add_action('wp_ajax_toggle_petcontact_access', 'toggle_petcontact_access_callback');
function toggle_petcontact_access_callback(){
    // 基础参数校验
    if(!isset($_POST['post_id']) || !isset($_POST['status']) || !is_user_logged_in()){
        wp_send_json_error('参数错误', 400);
    }
    $post_id = intval($_POST['post_id']);
    $status = intval($_POST['status']);
    // 校验操作合法性:仅文章作者可修改对应petcontact类型文章的状态
    $post = get_post($post_id);
    if(!$post || $post->post_author != get_current_user_id() || $post->post_type != 'petcontact'){
        wp_send_json_error('无操作权限', 403);
    }
    // 将开关状态写入postmeta
    update_post_meta($post_id, '_petcontact_public_access', $status);
    wp_send_json_success(array('msg' => '状态更新成功'));
}

3. 前端JS处理开关切换请求

在作者页模板中添加JS代码,监听开关变化,发送AJAX请求更新状态,同步给用户操作反馈:

document.addEventListener('DOMContentLoaded', function(){
    const toggles = document.querySelectorAll('.access-toggle');
    toggles.forEach(toggle => {
        toggle.addEventListener('change', async function(){
            const postId = this.dataset.postid;
            const status = this.checked ? 1 : 0;
            const labelEl = this.nextElementSibling;
            // 请求过程中禁用开关,防止重复点击
            this.disabled = true;
            try{
                const formData = new FormData();
                formData.append('action', 'toggle_petcontact_access');
                formData.append('post_id', postId);
                formData.append('status', status);
                const res = await fetch('<?php echo admin_url("admin-ajax.php"); ?>', {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin'
                });
                const data = await res.json();
                if(!data.success) throw new Error(data.data);
                // 更新状态提示文字
                labelEl.textContent = status ? '公开访问已开启' : '公开访问已关闭';
            }catch(err){
                // 操作失败回滚开关状态
                this.checked = !this.checked;
                alert('状态更新失败,请重试');
            }finally{
                this.disabled = false;
            }
        })
    })
})

以上为原生JS版本,无需额外依赖,如果主题已加载jQuery可自行简化写法。

4. 实现关闭状态的文章重定向逻辑

在functions.php中添加模板重定向钩子,判断文章访问权限:

add_action('template_redirect', 'petcontact_access_redirect');
function petcontact_access_redirect(){
    // 仅对petcontact类型的单篇文章生效
    if(!is_singular('petcontact')) return;
    $post_id = get_the_ID();
    $is_public = get_post_meta($post_id, '_petcontact_public_access', true) ?: 1;
    // 公开状态直接放行
    if($is_public) return;
    // 文章作者本人访问时放行,方便预览和调整设置
    if(is_user_logged_in() && get_current_user_id() == get_post_field('post_author', $post_id)) return;
    // 其余访问者302跳转到网站首页
    wp_redirect(home_url(), 302);
    exit;
}

配置说明:如果需要新发布的文章默认关闭公开访问,将代码中读取meta值的默认返回值从1改为0即可。所有输出内容均做了实体转义,权限校验逻辑覆盖了跨用户篡改场景。

内容的提问来源于stack exchange,提问作者michael upton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 15:39:25