I have a book store on WooCommerce and I have created custom fields for book product:
I want to make products page look like:
/// Image /// (/br)
PROD.NAME(/br)
Author(/br)
Publisher, Year(/br)
Price and button Add to cart below
I use this code for displaying "Publisher, Year":
<?php
echo get_post_meta($post->ID, 'author', true);
echo ', ';
echo get_post_meta($post->ID, 'year', true);
?>
And all is fine, BUT if i had no Publisher set in custom field I got ", Year" string. And that's my question - is it possible to not show a comma, if first or second field is not being set and how to do this?
The problem is solved but may be some more extra - I think it is some kind of similar but I cant get it:
at the Single Product page it should be the list:
and same logic: if there is a field data it should show whole string and if not just dont show anything. For now I got:
(in this scenario I got no Year set but the string "Year: nothing " appears.
I'm not much into wordpress, but you can do something like:
<?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;
?>
As I said, I'm not much into wordpress and I use ==
operator. You can make it more strict if you know what is returned by get_post_meta()
on unset field (this can be either NULL, empty string, FALSE...) and use ===
operator.
When it comes to your second question... it shouldn't be a problem...
<?php
//assign variables with get_post_meat as before...
if ($author != '')
echo 'Author: '.$author;
if ($publisher != '')
echo 'Publisher: '.$publisher;
if ($year != '')
echo 'Year: '.$year;
?>
I suggest you read PHP manual, especially section about flow control.