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

如何在WordPress Automattic AMP插件的amp single.php中添加元字段?

How to Add Custom Post Meta to Automattic AMP Plugin Templates

Got it, let's solve this issue. The Automattic AMP plugin uses a template context system that wraps post data into its own object (hence the $this->get() syntax), which is why the standard get_post_meta() call might not work as expected in your amp/single.php template. Here's how to properly inject and access your custom fields:

Step 1: Inject Custom Meta into the AMP Template Context

First, you need to hook into the plugin's data filter to add your post meta to the context that the AMP template uses. Add this code to your theme's functions.php file:

add_filter( 'amp_post_template_data', 'inject_custom_amp_post_meta', 10, 2 );
function inject_custom_amp_post_meta( $template_data, $post ) {
    // Replace 'field_name' with your actual custom meta key
    $template_data['my_custom_meta'] = get_post_meta( $post->ID, 'field_name', true );
    
    // Add more fields here if needed, e.g.:
    // $template_data['another_custom_field'] = get_post_meta( $post->ID, 'another_field', true );
    
    return $template_data;
}

This filter passes the current post object and the existing template data, allowing you to append your custom meta values to the data the template will use.

Step 2: Access the Custom Meta in Your AMP Template

Now you can retrieve the custom field in your amp/single.php template using the same $this->get() syntax you're familiar with. For meta tags, you might do something like this:

<?php 
// Get the custom meta value (escape it for security!)
$custom_meta = $this->get( 'my_custom_meta' );

// Only output the meta tag if the field has a value
if ( ! empty( $custom_meta ) ) : ?>
    <meta property="your:custom-meta" content="<?php echo esc_attr( $custom_meta ); ?>">
<?php endif; ?>

Why This Works

The AMP plugin's template system relies on a centralized data object (accessed via $this) instead of directly using the global $post variable in all cases. By using the amp_post_template_data filter, you're adding your custom meta to that centralized data, making it available via $this->get() in the template.

Alternative: Directly Access the Post Object (If Available)

In some cases, the global $post object might still be accessible in the AMP template. If you want to test this, you could try:

<?php 
global $post;
$custom_meta = get_post_meta( $post->ID, 'field_name', true );
if ( ! empty( $custom_meta ) ) : ?>
    <meta property="your:custom-meta" content="<?php echo esc_attr( $custom_meta ); ?>">
<?php endif; ?>

However, using the filter method is more reliable because it aligns with the plugin's intended data flow and ensures compatibility with future updates.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:38:30