哪种方法最适合从Wordpress帖子中的自定义字段中检索信息以显示在另一个页面上?

时间:2017-09-15 10:53:15

标签: php wordpress

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

我尝试了几种不同的方法,发现有两种方法可行。但是,由于我是初学者,我想知道这些方法是否“正确”?

这是我找到的一个解决方案,但它并不完全优雅:

byte buf [] = message.getBytes ();
output.write(buf);

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

// 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>';

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

// 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>';
}

方法3对我来说似乎最好。这是解决这个问题的好方法吗?如果有人能够解释方法2的问题,我也会很感激。感谢

2 个答案:

答案 0 :(得分:0)

在此处查看自定义字段套件文档: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>';

聚苯乙烯。不要忘记查看标题标记的顺序(<h1>之前应该<h2>

答案 1 :(得分:-1)

对于你的“方法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;
    }
}