【发布时间】: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 有什么问题,我也将不胜感激。谢谢
【问题讨论】:
-
您解决了吗?如果有帮助,别忘了给答案投票;-)