I'm a PHP beginner working with Wordpress, and I'm trying to retrieve data from custom fields (using Custom Field Suite) from a post to be displayed on a different page.
I have tried a few different ways, and found two methods that work. But as I'm a beginner, I wonder if these methods are 'proper'?
This is one solution I found, but it's not exactly elegant:
// 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>';
I tried to re-write it like this, but nothing is displayed - not sure what's wrong with this loop:
// 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>';
}
As method 2 wasn't working, I tried something else and found that this also works (I added the loop here based on this answer: 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();
?>
Method 3 seems best to me. Is this a good way of approaching this problem? And if anyone would be kind enough to explain what's wrong with method 2, I would also appreciate it. Thanks
Looking at the Custom Field Suite documentation here: http://customfieldsuite.com/api/get.html
It looks like you should be using the 'get' method:
CFS()->get( $field_name, $post_id, $options );
Eg.
$current = CFS()->get( 'get_current' );
echo '<h2>' . CFS()->get( 'current_title', $current ) . '</h2>';
echo '<h1>' . CFS()->get( 'current_artist', $current ) . '</h1>';
Ps. Don't forget to watch the order of your heading tags ( <h1>
should come before <h2>
)
In the case of your "method 2": what if you try rewriting it something like this?
// 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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.