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

WordPress:通过文章Slug转换为ID并跳转至前端编辑页方案问询

实现Slug转文章ID并跳转的前置页面

1. 前端表单页面

创建一个自定义页面模板(比如命名为page-slug-converter.php),用于让用户输入文章Slug:

<?php
/*
Template Name: Slug转文章ID跳转页
*/
get_header();
?>

<div class="slug-input-wrap">
    <h3>输入文章Slug</h3>
    <form method="POST" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="slug_to_post_id">
        <input type="text" name="post_slug" placeholder="请输入文章Slug" required>
        <button type="submit">进入编辑页</button>
    </form>
    <?php if (isset($_GET['err'])) : ?>
        <p style="color: #dc3232;">未找到对应文章,请检查Slug是否正确</p>
    <?php endif; ?>
</div>

<?php get_footer(); ?>

之后在WordPress后台创建一个页面,选择这个模板作为页面模板。

2. 后端Slug处理逻辑

在主题的functions.php中添加处理函数,接收表单提交的Slug并转换为文章ID:

// 处理Slug转ID请求(登录/未登录用户均可访问)
add_action('admin_post_slug_to_post_id', 'handle_slug_to_post_id');
add_action('admin_post_nopriv_slug_to_post_id', 'handle_slug_to_post_id');

function handle_slug_to_post_id() {
    // 校验Slug输入
    if (empty($_POST['post_slug'])) {
        $redirect_url = add_query_arg('err', 1, get_permalink(get_page_by_path('slug-converter')));
        wp_redirect($redirect_url);
        exit;
    }

    $post_slug = sanitize_text_field($_POST['post_slug']);
    
    // 方式1:通过url_to_post_id转换
    $post_url = home_url("/{$post_slug}/");
    $post_id = url_to_postid($post_url);

    // 方式2:直接查询数据库(效率更高,支持指定文章类型)
    // $target_post = get_page_by_path($post_slug, OBJECT, 'post'); // 替换'post'为你的自定义文章类型
    // $post_id = $target_post ? $target_post->ID : 0;

    // 校验是否找到对应文章
    if (!$post_id) {
        $redirect_url = add_query_arg('err', 1, get_permalink(get_page_by_path('slug-converter')));
        wp_redirect($redirect_url);
        exit;
    }

    // 跳转到编辑页面并携带文章ID参数
    $edit_page_url = home_url('/your-edit-page/?post_id=' . $post_id); // 替换为你的编辑页面URL
    wp_redirect($edit_page_url);
    exit;
}

3. 编辑页面获取文章ID

在你的前端编辑表单页面中,通过URL参数获取文章ID,用于ACF字段操作:

<?php
// 获取URL传递的文章ID
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
    $target_post_id = intval($_GET['post_id']);
    // 后续ACF操作示例:
    // $field_value = get_field('your_acf_field_name', $target_post_id);
    // update_field('your_acf_field_name', $new_value, $target_post_id);
} else {
    echo '<p>无效的文章ID,请返回重新输入Slug</p>';
}
?>

注意事项

  • 替换代码中的your-edit-page为你实际的编辑页面Slug或完整URL;
  • 如果使用自定义文章类型,在get_page_by_path函数的第三个参数指定对应的文章类型(比如'product');
  • 可根据需求添加权限校验,比如在处理函数开头加入if (!current_user_can('edit_posts')) wp_die('无访问权限');。

内容的提问来源于stack exchange,提问作者Brúnó Szubally

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:18:08