在内容之前插入自定义字段值

时间:2018-01-16 14:28:04

标签: php wordpress custom-fields add-filter

我有一个自定义元字段,我想自动插入the_content,以便我的AMP插件可以像the_content一样呈现自定义字段值。

目前我正在使用此代码来显示它:

<?php $video_value = get_post_meta( get_the_ID(), '_video', true ); ?>

<?php if ( ! empty( $video_value ) ) {?>
    <div class="video-container"><?php echo $video_value; ?></div>
<?php } else { ?>
    <?php the_post_thumbnail(); ?>
<?php } ?>

但我希望在$video_value之前自动插入the_content

2 个答案:

答案 0 :(得分:2)

你可以这样做 -

并添加您想要的条件 -

您可能需要访问Global $ post才能获取元值

close

您可以在functions.php中添加它

答案 1 :(得分:2)

您可以使用function my_custom_content_filter($content){ global $post; $video_value = get_post_meta($post->ID, '_video', true); if($video_value){ return '<div class="video-container">' . $video_value . '</div>' . $content; }else{ return get_the_post_thumbnail($post->ID) . $content; } } add_filter('the_content', 'my_custom_content_filter'); 过滤器执行此操作。您可以在WordPress developer site上了解更多相关信息。

但代码可能看起来像这样:

functions.php

您可以在the_content()文件中添加此代码。

注意此过滤器仅适用于get_the_content()而非#parent { border: 1px solid red; height: 100vh; display: flex; align-items: center; /* vertical */ justify-content: center; /* horizontal */ } .child { border: 1px solid blue; }

相关问题