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

自定义AMP页面(无插件):添加AMP端点后如何获取文章ID?

解决AMP模板中无法获取文章ID的问题

核心原因

你遇到的global $post和get_the_ID()无效的情况,是因为自定义AMP endpoint加载模板时,主查询的$post对象尚未正确初始化,或者重写规则未生效导致查询参数丢失。

解决方案

1. 先刷新重写规则

添加自定义endpoint后,必须刷新WordPress的固定链接规则:

  • 进入后台「设置」→「固定链接」
  • 无需修改任何设置,直接点击「保存更改」即可完成规则刷新

2. 在AMP模板中获取文章ID的可靠方法

在amp-template.php中,通过以下两种方式获取文章ID:

方法一:使用get_queried_object()(推荐)

这个函数会直接返回当前查询的对象(文章、页面、分类等),是最可靠的方式:

// 获取当前查询的对象
$queried_obj = get_queried_object();

// 判断是否为文章/页面对象
if ($queried_obj instanceof WP_Post) {
    $post_id = $queried_obj->ID;
    // 示例:获取文章标题和内容
    $post_title = get_the_title($post_id);
    $post_content = apply_filters('the_content', get_post_field('post_content', $post_id));
}

方法二:直接获取查询变量

文章页面的查询参数中会包含p(文章ID)或page_id(页面ID),可以直接读取:

// 优先获取文章ID
$post_id = get_query_var('p');
// 如果是页面,读取page_id
if (empty($post_id)) {
    $post_id = get_query_var('page_id');
}

if (!empty($post_id)) {
    // 在这里使用$post_id获取文章数据
    $post = get_post($post_id);
}

3. 可选:调整模板加载优先级

如果上述方法仍无效,可以尝试调整template_include的优先级,确保模板在主查询初始化后加载:

// 将优先级从2改为10
add_filter('template_include', 'amp_page_template_pinup', 10);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:05:22