正在使用输出的字符串print_r()
是称为序列化字符串的内容。当WordPress在1个自定义字段中存储一个值数组时,它会使用一个名为serialize()
你想做的是unserialize
字符串,然后可以访问数组中的每个“关联索引”。
通常get_post_meta()
为您取消序列化字符串,但它看起来像自定义函数GetSettings::getPostMeta()
没有。在这种情况下,我们可以运行maybe_unserialize()
如果能够,它将转换为可用的数组。
然后我们可以简单地在数组中循环,输出所需的内容。
$aCoupon = GetSettings::getPostMeta($post->ID, \'coupon\');
$aCoupon = maybe_unserialze( $aCoupon );
if ( empty( $aCoupon ) ){
foreach ( $aCoupon as $key => $value ) {
echo \'<div><span class="label">\' . $key . \'</span> \' . $value . \'</div>\';
}
}
根据您的示例,它将输出如下内容。
<div><span class="label">highlight</span> Test Highlight</div>
<div><span class="label">title</span> 50% off food</div>
<div><span class="label">description</span> Test description</div>
<div><span class="label">code</span> 1524521</div>
<div><span class="label">popup_image</span> 4548</div>
<div><span class="label">popup_description</span> Popup description</div>
<div><span class="label">redirect_to</span> </div>
或者,如果要直接访问1个值。
$aCoupon = GetSettings::getPostMeta($post->ID, \'coupon\');
$aCoupon = maybe_unserialze( $aCoupon );
if ( empty( $aCoupon ) ){
//If the title is set, and is not empty, output it.
if ( isset( $aCoupon[\'title\'] ) && \'\' !== $aCoupon[\'title\'] ) {
echo \'<div><span class="label">Title</span> \' . $aCoupon[\'title\'] . \'</div>\';
}
}
@Shaun21uk编辑-我做了一些小改动(下面是完整代码)。不管什么原因
$aCoupon = GetSettings::getPostMeta($coupon_id, \'coupon\');
我仍然想知道如何利用主题处理数据的方式。
您的短代码函数应该如下所示:
add_shortcode( \'qg_shortcode\', \'qg_shortcode\' );
function qg_shortcode() {
$q = new WP_Query(array(
\'post_type\' => \'listing\',
\'posts_per_page\' => 5,
\'meta_key\' => \'wc_coupon\',
\'meta_value\' => \' \',
\'meta_compare\' => \'!=\'
));
if ( $q->have_posts() ) :
while ( $q->have_posts() ) : $q->the_post();
echo \'<h2 class="text-center"><a href="\' . get_permalink() . \'">\';
the_title();
echo \'</a></h2>\';
the_content();
// Get the ID of the attached coupon.
$coupon_id = get_post_meta( get_the_ID(), \'wc_coupon\', true );
// Get the coupon details from the coupon using the coupons ID.
$aCoupon = maybe_unserialize( $coupon_id );
// This checks if the coupon details are NOT empty, if that is true, then output the info.
if ( ! empty( $aCoupon ) ) {
// If the title is set, and is not empty, output it.
if ( isset( $aCoupon[\'title\'] ) && \'\' !== $aCoupon[\'title\'] ) {
echo \'<div><span class="label">Title</span> \' . $aCoupon[\'title\'] . \'</div>\';
}
}
echo\'<div class="offer-button">\';
echo\'<a href="\' . get_permalink() . \'" class="offer-button-text">Claim this offer!</a>\';
echo\'</div>\';
endwhile;
wp_reset_postdata();
endif;
}