我认为我们可以做得更好更安全一些。我们可以一次性获得所有的post meta(这只是让你的代码干涸一点,请参见this post on custom field performance)。
我们可以尝试以下操作:(代码在执行过程中会被注释,请注意,所有代码都未经测试)
选项1-呼叫get_post_meta()
一次
$meta = get_post_meta( get_the_ID() );
// First make sure we have data before continuing
if ( $meta ) :
// Get your field values and set defaults
$fields = [];
$field_names = [\'Client\', \'Tools\', \'About\', \'Process\'];
foreach ( $field_names as $field_name ) {
if ( \'About\' === $field_name ) {
$name = \'AboutTheProject\';
} else {
$name = $field_name;
}
$fields[$field_name] = ( isset( $meta[\'fbb_ProjectData_\' . $name] ) )
? filter_var( $meta[\'fbb_ProjectData_\' . $name][0], FILTER_SANITIZE_STRING )
: \'\';
}
// Lets make sure we have at least one key/value pair with avalue
if ( array_filter( $fields ) ) : ?>
<div id="fbb_ProjectDataWrap">
<?php // Lets loop through $fields and display them
foreach ( $fields as $key=>$field ) :
// Make sure $field is not empty, if so, continue
if ( !$field )
continue;
// We have values, lets display them
?>
<div id="fbb_ProjectData_<?php echo $key; ?>" class="fbb_ProjectDataSetSection">
<div class="fbb_Title">
<h5><?php echo $key; ?>:</h5>
</div>
<ul>
<li>
<div>
<?php echo $field; ?>
</div>
</li>
</ul>
</div>
<?php endforeach; ?>
</div>
<?php
endi
f;endif;
选项2-呼叫get_post_meta()
对于每个键,因为自定义字段是缓存的,如果调用get_post_meta()
(参见链接帖子),我们可以get_post_meta()
对于每个键。只需记住设置$single
到true
// Get your field values and set defaults
$fields = [];
$field_names = [\'Client\', \'Tools\', \'About\', \'Process\'];
foreach ( $field_names as $field_name ) {
if ( \'About\' === $field_name ) {
$name = \'AboutTheProject\';
} else {
$name = $field_name;
}
$fields[$field_name] = filter_var(
get_post_meta( get_the_ID(), \'fbb_ProjectData_\' . $name, true ),
FILTER_SANITIZE_STRING
);
}
// Lets make sure we have at least one key/value pair with avalue
if ( array_filter( $fields ) ) : ?>
<div id="fbb_ProjectDataWrap">
<?php // Lets loop through $fields and display them
foreach ( $fields as $key=>$field ) :
// Make sure $field is not empty, if so, continue
if ( !$field )
continue;
// We have values, lets display them
?>
<div id="fbb_ProjectData_<?php echo $key; ?>" class="fbb_ProjectDataSetSection">
<div class="fbb_Title">
<h5><?php echo $key; ?>:</h5>
</div>
<ul>
<li>
<div>
<?php echo $field; ?>
</div>
</li>
</ul>
</div>
<?php endforeach; ?>
</div>
<?php
endif;