Display Product Attribute Value only if it exists - php

Surprisingly can't find anything on this... basically I call my custom product attributes on the product view page like this:
Men / Women: <?php echo $this->htmlEscape($_product->getmenwomen()) ?>
This displays the men/women attribute fine, but these are optional values, so if a product doesn't have a value for this particular attribute, the line is still displayed, just with no value:
Men / Women:
I'd like that line to not show at all if there is indeed, no value for a product. Any ideas?

You have to check if the value of getmenwomen() really contains something you expect it to contain (eg men/women) before printing it. In this example i presume that anything but whitespace is a valid value.
$menwomen = $_product->getmenwomen();
if (trim($menwomen)) {
echo "Men / Women: ".$this->htmlEscape($menwomen);
}

Not 100% on this because I am not sure if getmenwomen() will return false if its empty
If nothing is to be returned, by default it should return false.
<?php
if ($var = $this->htmlEscape($_product->getmenwomen()) {
echo "Men / Women: " + $var;
}
?>

You mean you want to display everything if there is a value and nothing if there isn't? Just add a simple conditional:
if (!empty($this->htmlEscape($_product->getmenwomen())))
echo 'Men / Women: '.$this->htmlEscape($_product->getmenwomen());
and that's it, you don't even need an else in there.

Related

Show only column value; not column name in Yii

I'm trying to modify a script written in php, js with Yii. I simply need the value that I'm outputting to show up as a number without the column header. In this case, the number would be 20.
I'm using formulas.php to get the value that I need:
public function getMarkup()
{
$mid=$this->getMerchantID();
$DbExt=new DbExt;
$stmt="SELECT markup FROM
{{merchant}}
WHERE
merchant_id='$mid'
LIMIT 0,1
";
if ( $res=$DbExt->rst($stmt)){
return $res[0];
}
return false;
}
Then I'm calling the value on another page as:
<?php
$anArray2=Yii::app()->functions->getMarkup();
echo json_encode($anArray2);
?>
This returns:
{"markup":"20"}
I tried changing it to:
<?php
echo Yii::app()->functions->getMarkup();
?>
And that returns:
Array
I'm trying to get it to return with just 20 (the value of the column) without the column header.
<?php
echo Yii::app()->functions->getMarkup()["markup"];
?>
Is that what you're looking for?

Use only function parameter if variable has a value

I'm developing a small system to add records which be can opened later. On the page view.php it shows all records of all different country. I just extend this to only show one selected countries.
I call this function with the following argument:
$toxRecords->getStatsCountry();
If I want to show only one country, I just simple add the county code as parameter. Example:
$toxRecords->getStatsCountry('NL');
Because I use one page to show all countries but also one specific country it needs to check if there is an variable.
I check my POST with the following argument: toxInput::get('country');
This just simple return: $_POST['country'].
Now I just want that it will only use the function parameter if value country exists. This can be very simple, see below:
if($country = toxInput::get('country')) {
$toxList = $toxRecords->getRecords($country);
} else {
$toxList = $toxRecords->getRecords();
}
But I was wondering if it possible to shorten this to one single lane?
Example what I tried and will explain what I want:
$toxRecords->getRecords(if($country = toxInput::get('country')){ echo $country; });
this statement returns only one value through the condition:
condition ? value if condition is true : value if condition is false
for example:
$toxRecords->getRecords($country == toxInput::get('country') ? $country : "");
Try something like this:
($val1 == $val2)? Echo "true" : Echo "False";
For more info check this post:
https://stackoverflow.com/a/1506621/7116840

PHP/Wordpress: IF/ELSE executing both conditions

Have been reading through multiple similar questions and went over my syntax many times, but I can't figure out why my PHP code is executing both conditions.
I'm trying to replace the url of an element with the string from a custom field if the field is not empty. If the field is empty, I want to output the permalink normally. What happens is that the code concatenates both the string from the custom field and the permalink when the field is not empty. If i remove the string in the field, it works fine.
<div class="profile-content">
<a href="
<?php
if ( the_field('direct_resource_link') != '') {
the_field('direct_resource_link');
} else {
the_permalink($id);
} ?>
"><h5><?php the_title(); ?></h5></a>
<div class="profile-footer">
Thanks!
Dan.
EDIT after comment from original poster
My initial assessment (left below for reference) was correct. You are using function that will print/echo content instead of returning it. Your if will always evaluate to false, because you are calling function that returns nothing; and PHP thinks that nothing and empty string are the same thing.
You didn't see that when field was empty, because the_field() for empty field printed empty string (or nothing at all), i.e. it didn't modify value printed by the_permalink() in any way/
According to ACF documentation, the_field() is accompanied by get_field() which returns value instead of printing it.
Your code should look like that:
<div class="profile-content">
<a href="
<?php
if ( get_field('direct_resource_link') ) {
the_field('direct_resource_link');
} else {
the_permalink($id);
} ?>
"><h5><?php the_title(); ?></h5></a>
<div class="profile-footer">
My initial post
What happens is that you run function the_field('direct_resource_link') and compare it's return value to ''; if that value is empty, you run the_permalink($id);.
It's hard to tell what the_field() is and what it is supposed to do, but I guess that it prints value instead of returning it. So if field is empty, it prints nothing, resulting in pure run of the_permalink(). If field is not empty, it prints it content and returns nothing. Since nothing is equal to empty string, PHP proceeds with else branch and invokes the_permalink() that prints additional info.
Solution: modify the_field() to return value instead of printing it, or make additional function that will query for value and return it, and use that function in if statement.
Miroslaw Zalewski already answered your question here, so this is simply to show you the kind of code needed to fix your issue:
function get_the_field($field) {
ob_start();
the_field($field);
return ob_get_clean();
}
This code will start an output buffer (which will capture all echo'd data), run the_field and return (and delete) the output buffer (the echo'd data from the_field). This means you can simply do the following:
...
<?php
$theField = get_the_field('direct_resource_link');
if ( $theField != '') {
echo $theField;
} else {
the_permalink($id);
}
?>
...
This can all be simplified. the_field() echoes a meta value. You don't want that...Instead, you want to return the value to check it, before conditionally echoing it. You can do this using get_field().
In the simplest form, your final code would look like the following:
<a href="<?php get_field('direct_resource_link') ? the_field('direct_resource_link') : the_permalink($id); ?>">
<h5><?php the_title(); ?></h5>
</a>

Variable inside a php echo function

I have a php function which displays a rating bar with the arguments. I have a variable called itemID inside my php page which holds the unique item number. I need to send this value to my function and also echo command must stay. Is there a way to achieve this?
Here is the code, which does not work. When I try it on the server, it does not show the id of item, it prints the variable name as it is.
<?php echo rating_bar('$as',5) ?>
What I get at html file:
<div id="unit_long$as">
instead of the item id in place of $as.
Single Quotes do not support variable replace,
$as = "test";
echo '$as'; //$as in your end result
echo "$as"; // test in your end result
echo $as; // test in your end result
//For proper use
echo " ".$as." "; // test in your end result
Update for newer PHP versions you should now use Template Syntax
echo "{$as}"
If I get what you are saying, this is what you are asking.
<?php echo rating_bar($itemID,5); ?>
With the limited code you are providing, thats what looks like you are asking.

Wordpress - Display text if checkbox output matches the page title

I want to show the projects that has had it's checkbox ticked as Branding, if it's on the Branding page (i.e the page title is Branding).
To explain the code a bit:
This line show's all the checkboxes that have been ticked for each project so it will output "Branding", "Web", "Print" if they have been ticked.
implode(', ',get_field('categories')
This next line is just checking the page title is "Branding":
implode(', ',get_field('categories')
I'm trying to put these both in an if statement where it would just output the checked boxes and if they match the title then output them.
<?php if(implode(', ',get_field('categories')) && $grid_title == "Branding"); {
echo "testing";
}
?>
The code above shows what I want to do but it doesn't quite work.
IMPORTANT: I'm using this plugin to create the custom checkboxes so please bear that in mind.
=============================
UPDATE:
Thanks very much to Adam Kiss for solving what I asked, small update to question:
How could I code this neatly - using your answer, Branding was just one example of the check boxes, there's also several other one's like Web, Print, Social so how could I match those to the page title as well?
So it will be along the lines of if checked field equals the page title "branding" do OR checked field equals page title "web" OR checked field equals page title "print".
the function you're looking for is in_array:
<?php
if(
in_array("Branding", get_field('categories'))
&& $grid_title == "Branding"
){
echo "testing";
}
Note: this assumes that result of that implode is array with strings like "Branding", "Web", etc.
Edit: Since we're using implode(), I assume get_field returns type array, so we put the implode away (I got confused for a while)
Edit: Sorry, was away :]
you could use array_intersect
Usage:
$categories = get_field('categories');
$cats_iwant = array("Branding", "Print", "Design");
$inarray = array_intersect($categories, $cats_iwant);
//this '$inarray' now has values like 'Branding', 'Design' which are in both arrays
if (count($inarray) > 0) {
//we have at least one common word ('Branding', ...)
}
//short version
if (count(array_intersect(get_field('categories'),array(
'Branding', 'Design', 'Print'
))) > 0)
{
//do stuff
}

Categories