为一篇文章显示多个自定义字段

问题描述 投票:0回答:1

我有两个“自定义字段”分配给我的帖子。这两个“自定义字段”具有相同的名称,但“值”不同。目前,我下面的代码仅显示其中一个链接。我正在尝试让它显示两者。因此,每当我添加另一个名为“精选博客”的“自定义字段”时,它都会继续显示所有这些内容。

自定义字段的
1) 名称:特色博客和值:704(704是帖子ID)
2) 名称:特色博客和价值:699(699是帖子ID)

用于显示每个帖子的链接的代码。 (只能获取其中一个自定义字段来显示)

输出截图

正在使用的代码

<?php $related = get_post_meta($post->ID, "Featured-Blog", $single=true);

        $related=explode(',',$related);
        $args = array_merge( array('post__in'  => $related, $wp_query->query ) );
        query_posts($args);
        if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

        <div id="<?php the_ID(); ?>">
            <a href="<?php the_permalink();?>"><p class="caption"><?php the_title(); ?></p></a>
        </div>

    <?php endwhile; else: ?>
    <p>no related</p>
    <?php endif; wp_reset_query();?>

下面是我最初尝试使用但最终没有使用的旧代码。这实际上确实拉动了我的两个“自定义字段”。您可以看到它的编码明显不同,因为您可以看到它显示“标题”而不是帖子标题。但我只是使用这段代码作为示例,向您展示可以显示多个“自定义字段”,除非下面的代码有一个简单的修复方法?也许某些代码形式可以合并到我上面的工作脚本中。上面的代码和下面的代码都非常接近我想要做的事情。看起来一个人有另一个人需要的东西。

输出截图

<div id="related-posts">
<?php
  $custom_fields = get_post_custom($post_id); //Current post id
  $my_custom_field = $custom_fields['Featured-Blog']; //key name
  foreach ( $my_custom_field as $key => $url )
 echo $key ="<a href='".$url."'>TEST</a><br /><br /><br/>";
?>
php wordpress custom-fields
1个回答
1
投票

使用

false
 时,您只需传递 true
 而不是 
get_post_meta()
:

$related = get_post_meta( $post->ID, "Featured-Blog", false );
var_dump( $related );

使用

var_dump
,您将能够看到变量的原始内容。不管怎样,你会收到一个数组,所以你可以简单地这样做:

$related = get_post_meta( $post->ID, "Featured-Blog", false );
$args = array_merge( array('post__in'  => $related, $wp_query->query ) );
另一方面,

get_post_custom
,抓取帖子的所有自定义字段并在最后生成相同的结果,它只需要一个额外的命令来获取值。

请注意 您不应该使用
query_posts

© www.soinside.com 2019 - 2024. All rights reserved.