在内容之前插入自定义字段值
Insert custom field value before content
我有一个自定义元字段,我想将其自动插入到 the_content 中,以便我的 AMP 插件能够以与 the_content.[=13= 相同的方式呈现自定义字段值]
目前我正在使用这段代码来显示它:
<?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
之前。
你可以这样做 -
并添加您想要的条件 -
您可能需要访问全局 $post 以获取元值
function custom_weird_name_before_after($content) {
if(is_page() || is_single() || $yourOwnConditions == true) {
$beforecontent = 'This line will go before the content - populate with whatever.';
$aftercontent = 'This will come after the content - makes sense right?';
$fullcontent = $beforecontent . $content . $aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter('the_content', 'custom_weird_name_before_after');
您可以在 functions.php
中添加这个
您可以使用 the_content
过滤器来执行此操作。您可以在 WordPress developer site.
上阅读更多相关信息
但代码可能看起来像这样:
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');
您可以在 functions.php
文件中添加此代码。
注意 此过滤器仅适用于 the_content()
而不适用于 get_the_content()
我有一个自定义元字段,我想将其自动插入到 the_content 中,以便我的 AMP 插件能够以与 the_content.[=13= 相同的方式呈现自定义字段值]
目前我正在使用这段代码来显示它:
<?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
之前。
你可以这样做 -
并添加您想要的条件 -
您可能需要访问全局 $post 以获取元值
function custom_weird_name_before_after($content) {
if(is_page() || is_single() || $yourOwnConditions == true) {
$beforecontent = 'This line will go before the content - populate with whatever.';
$aftercontent = 'This will come after the content - makes sense right?';
$fullcontent = $beforecontent . $content . $aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter('the_content', 'custom_weird_name_before_after');
您可以在 functions.php
中添加这个您可以使用 the_content
过滤器来执行此操作。您可以在 WordPress developer site.
但代码可能看起来像这样:
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');
您可以在 functions.php
文件中添加此代码。
注意 此过滤器仅适用于 the_content()
而不适用于 get_the_content()