我在WooCommerce上有一个书店,我为书籍产品创建了自定义字段:
我想让产品页面看起来像:
/// Image /// (/br)
PROD.NAME(/br)
Author(/br)
Publisher, Year(/br)
Price and button Add to cart below
我使用此代码显示“Publisher,Year”:
<?php
echo get_post_meta($post->ID, 'author', true);
echo ', ';
echo get_post_meta($post->ID, 'year', true);
?>
一切都很好,但如果我在自定义字段中没有设置发布者,我会收到“,年”字符串。这是我的问题 - 是否可能不显示逗号,如果没有设置第一个或第二个字段以及如何执行此操作?
问题已经解决,但可能会有一些额外的问题 - 我认为它有点类似,但我无法得到它:
在单品页面上应该是列表:
和相同的逻辑:如果有一个字段数据,它应该显示整个字符串,如果不是只是不显示任何东西。现在我得到了:
(在这种情况下,我没有设置年份,但字符串“Year: nothing ”出现。
答案 0 :(得分:0)
我对wordpress并不多,但你可以做类似的事情:
<?php
//I assume you meant publisher, not author
$publisher = get_post_meta($post->ID, 'publisher', true);
$year = get_post_meta($post->ID, 'year', true);
if (($publisher == '') || ($year == ''))
echo $publisher.$year;
else
echo $publisher.', '.$year;
?>
正如我所说,我对wordpress并不多,而且我使用==
运算符。
如果您知道get_post_meta()
在未设置字段上返回的内容(可以是NULL,空字符串,FALSE ...)并使用===
运算符,则可以使其更严格。
说到你的第二个问题......这应该不是问题......
<?php
//assign variables with get_post_meat as before...
if ($author != '')
echo 'Author: '.$author;
if ($publisher != '')
echo 'Publisher: '.$publisher;
if ($year != '')
echo 'Year: '.$year;
?>
我建议您阅读PHP manual,尤其是关于flow control的部分。