What would be the best way to write this block of PHP instead of listing each number??
<?php $name1 = get_post_meta(get_the_ID(), 'ch_client_name1', TRUE);
$name2 = get_post_meta(get_the_ID(), 'ch_client_name2', TRUE);
$name3 = get_post_meta(get_the_ID(), 'ch_client_name3', TRUE);
$name4 = get_post_meta(get_the_ID(), 'ch_client_name4', TRUE);
$name5 = get_post_meta(get_the_ID(), 'ch_client_name5', TRUE);
?>
And here is the HTML that I will be using. So I will want the list to display each of the 5 names.
<li id="<?php the_ID(); ?>" ">
<?php echo $name1; ?>
</li>
This will work:
for($i=1;$i<=5;$i++){
${'name'.$i} = get_post_meta(get_the_ID(), 'ch_client_name'.$i, TRUE);
}
$names = array('ch_client_name1', 'ch_client_name2', 'ch_client_name3', 'ch_client_name4', 'ch_client_name5' )
foreach($names as $name) {
$realname = get_post_meta(get_the_ID()), $name, TRUE);
echo '<li id="'. theID() .'">'. $realname .'</li>';
}
You can do like it:
<?php
for($i = 1; $i <= 5; $i++) {
$nameN = "name{$i}";
$$nameN = get_post_meta(get_the_ID(), "ch_client_name{$i}", TRUE);
// or $name[$i], if you can
?>
<li id="<?php the_ID(); ?>">
<?php echo $$nameN; ?>
</li>
<?php
}
<?php
$numberOfNames=5;
$names = array();
for($i=1; $i<=$numberOfNames; $i++)
$names[] = get_post_meta(get_the_ID(), 'ch_client_name'.$i, TRUE);
foreach($names as $k=>$name){
echo "<li id=\"".($k+1)."\">\n$name\n</li>";
}
?>
You might even want to consider using this, which gets all post meta (custom) fields at once:
$meta = get_post_custom( $post_id = get_the_ID() );
for( $i = 1; $i <= 5; $i++ )
echo '<li id="client-'.$post_id.'-'.$i.'">'.$meta["ch_client_name{$i}"].'</li>';
Note I also fixed an error in the question when he asked for this:
<li id="<?php the_ID(); ?>" ">
The problems I fixed were:
"client-{$post_id}-"
) , and the_ID()
returns the post ID for each of the five (5) results instead of having a unique value that is required for @id attributes.
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.