【问题标题】:Which method is best for retrieving information from custom fields in a Wordpress post to be displayed on another page?哪种方法最适合从 Wordpress 帖子中的自定义字段中检索信息以显示在另一个页面上?
【发布时间】:2017-09-15 10:53:14
【问题描述】:

我是一名使用 Wordpress 的 PHP 初学者,我正在尝试从帖子中的自定义字段(使用自定义字段套件)检索数据以显示在不同的页面上。

我尝试了几种不同的方法,并找到了两种可行的方法。但作为一个初学者,我想知道这些方法是否“正确”?

这是我找到的一种解决方案,但它并不十分优雅:

// Method 1
$current = CFS()->get( 'get_current' ); //retrieves the post ID from a custom field on the page
$custom_fields = get_post_custom($current);
$my_custom_field = $custom_fields['current_title'];
$my_custom_field2 = $custom_fields['current_artist'];

foreach ( $my_custom_field as $key) {
}
foreach ( $my_custom_field2 as $key2) {
}

echo '<h2>'.$key.'</h2>';
echo '<h1>'.$key2.'</h1>';

我试图像这样重写它,但没有显示任何内容 - 不确定这个循环有什么问题:

// Method 2
$current = CFS()->get( 'get_current' ); 
$custom_fields = get_post_custom($current);

foreach ( $custom_fields as $key) {

echo '<h2>'.$key['current_title'].'</h2>';
echo '<h1>'.$key['current_artist'].'</h1>';
}

由于方法 2 不起作用,我尝试了其他方法,发现这也有效(我根据此答案在此处添加了循环:https://stackoverflow.com/a/19918170/5483154):

 // Method 3
 <?php while ( have_posts() ) : the_post();
 $current = CFS()->get( 'get_current' );
 $currentitle = get_post_meta($current, 'current_title', true);
 $artistname = get_post_meta($current, 'current_artist', true);

 echo '<h2>'.$currentitle.'</h2>';
 echo '<h1>'.$artistname.'</h1>';

 endwhile;
 wp_reset_query();
 ?>

方法 3 对我来说似乎是最好的。这是解决这个问题的好方法吗?如果有人愿意解释方法 2 有什么问题,我也将不胜感激。谢谢

【问题讨论】:

  • 您解决了吗?如果有帮助,别忘了给答案投票;-)

标签: php wordpress


【解决方案1】:

在此处查看自定义字段套件文档:http://customfieldsuite.com/api/get.html

看来您应该使用“get”方法:

CFS()->get( $field_name, $post_id, $options );

例如。

$current = CFS()->get( 'get_current' );     

echo '<h2>' . CFS()->get( 'current_title', $current ) . '</h2>';
echo '<h1>' . CFS()->get( 'current_artist', $current ) . '</h1>';

附言。不要忘记查看标题标签的顺序(&lt;h1&gt; 应该在 &lt;h2&gt; 之前)

【讨论】:

    【解决方案2】:

    对于您的“方法 2”:如果您尝试像这样重写它会怎样?

    // Method 2
    $current = CFS()->get('get_current');
    $custom_fields = get_post_custom($current);
    
    foreach ($custom_fields as $field) {
        foreach ($field as $key => $value) {
            echo $key . ': ' . $value;
        }
    }
    

    【讨论】:

    • 这不是使用自定义字段套件获取自定义字段的推荐方式,并且可能 OP 希望按指定的顺序显示自定义字段,而不是按指定的顺序输出它们与 foreach 一起存储...始终最好遵循文档... ;-)
    • 你是对的 ?,虽然我是在回复发帖人的这个声明:“如果有人愿意解释方法 2 的问题,我也将不胜感激。谢谢”。好像发帖人误解了我试图在代码中显示的 get_post_custom() 返回数据的结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多