代码之家  ›  专栏  ›  技术社区  ›  Ciaran Gaffey

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

  •  0
  • Ciaran Gaffey  · 技术社区  · 6 年前

    我有一个自定义元字段,我想自动插入到\u内容中,以便我的AMP插件可以以与\u内容相同的方式呈现自定义字段值。

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

    <?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 回复  |  直到 6 年前
        1
  •  2
  •   zarex360    6 年前

    您可以使用 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()

        2
  •  2
  •   Stender    6 年前

    你可以这样做-

    并添加所需的条件-

    您可能需要访问Global$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');
    

    您可以在函数中添加此项。php