I have created 5 custom meta values for my products on WC but not every product have all custom fields.
At the moment, I am displaying the meta data like so:
<div class="meta">
<?php if($product->get_meta('metabox_animal') != '') echo '<div class="type"><p>Row One</p></div>' . $product->get_meta('metabox_animal'); ?>
<?php if($product->get_meta('metabox_medical') != '') echo '<div class="type"><p>Row Two</p></div>' . $product->get_meta('metabox_medical'); ?>
<?php if($product->get_meta('metabox_general') != '') echo '<div class="type"><p>Row Three</p></div>' . $product->get_meta('metabox_general'); ?>
<?php if($product->get_meta('metabox_capacity') != '') echo '<div class="type"><p>Row Four</p></div>' . $product->get_meta('metabox_capacity'); ?>
<?php if($product->get_meta('metabox_pet') != '') echo '<div class="type"><p>Row Five</p></div>' . $product->get_meta('metabox_pet'); ?>
</div>
Is there a way that I can create a loop that will cycle through all of the meta values and if they exist, display them but if they're blank / empty / not used show a container 'NOT APPLICABLE'?
Any help would be greatly appreciated!
This not tested and only one way you might get this done:
<?php
$html = '';
// collection of meta keys and their display label
$meta_keys_with_labels = [
['animal', 'Row One'],
['medical', 'Row Two'],
['general', 'Row Three'],
['capacity', 'Row Four'],
['pet', 'Row Five']
];
$html .= '<div class="meta">';
// loop to check if meta key/value exists and append to html string
foreach ($meta_keys_with_labels as $meta) {
// unpack the key and display label
[$key, $label] = $meta;
// grab meta value
$meta_value = $product->get_meta("metabox_$key");
// append meta value to html string
if (!empty($meta_value)) {
$html .= "<div class=\"type\"><p>$label</p></div>$meta_value";
}
}
$html .= '</div>';
echo $html;
Sure!
You can create an array of all the meta terms that you need to retrieve.
Following your code this is the code you will need. Of course you can add/remove as you see fit.
<?php
$meta_terms = [
'metabox_animal',
'metabox_medical',
'metabox_general',
'metabox_capacity',
'metabox_pet'
];
foreach ($meta_terms as $meta_term) {
$meta = $product->get_meta($meta_term);
if (!empty($meta)) {
echo '<div class="type"><p>' . $meta . '</p></div>';
}
}
So... what the hell did we do here?
First we created an array of all the meta data that we need to retrieve.
After we created that array we need to start an iteration to get, check and display each meta data.
For that we use a foreach (PHP foreach).
ok
In the foreach block, using the variable $meta_term that contains the meta string that we need to retrieve we now use it to get the product meta data.
Now we check if the meta data is not empty, using the !empty() function, if it's not empty than we know that there is value we can output so, using echo we can now build the proper html.
Hope this help =D
You can set your related data in an array, then use a foreach loop as follow and if a custom field value is empty or doesn't exist, "NOT APPLICABLE" will be displayed instead (code is commented):
<?php
// Data array with Meta key / Label pairs
$data = array(
'metabox_animal' => __("Row One"),
'metabox_medical' => __("Row Two"),
'metabox_general' => __("Row Three"),
'metabox_capacity' => __("Row Four"),
'metabox_pet' => __("Row Five"),
);
echo '<div class="meta">';
// Loop through the data array of Meta key / Label pairs
foreach ( $data as $meta_key => $label ) {
$meta_value = $product->get_meta($meta_key); // Get the meta value
$meta_value = empty($meta_value) ? __("NOT APPLICABLE") : $meta_value; // If empty show "NOT APPLICABLE"
echo '<div class="type"><strong>' . $label . '</strong>: ' . $meta_value . '</div>';
}
echo '</div>';
?>
I have changed a bit your html. If it's not convenient and you want to keep yours, just replace:
echo '<div class="type"><strong>' . $label . '</strong>: ' . $meta_value . '</div>';
by this line:
echo '<div class="type"><p>' . $label . '</p></div>' . $meta_value;
Related
Hi i have a function in PHP, which returns colors of my products in woocommerce.
My function:
global $product;
if ( $product->is_type('variable') ) {
$taxonomy = 'pa_color';
$colors = explode(',',$product->get_attribute($taxonomy));
echo '<div class="colour-swatch">';
foreach ($colors as $color) {
echo '<div class="swatch '. strtolower(trim($color)) .'">';
echo '<div class="circle">';
echo '<div style="background-color: var(--'. strtolower(trim($color)) .');"></div>';
echo '';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
What i need is make it count how many colors it finds inside the loop (so how many times the loop is done). And echo it below.
So if one loop is done, it should (echo "1 color").
If 2 or more colors is found it should echo "x colors" (so include the s on color to make it correct).
// To print the total size of the colors.(the number of times the loop ran)
$sz = sizeof($colors);
echo $sz . (($sz==1) ? " color" : " colors");
I treid to create loop for display Custom Fields on single page of post
<?php
$meta = get_post_meta($post->ID);
foreach($meta as $key=>$val)
{
echo '<li><span>' . $key . ' : </span>' . $val[0] . '</li>';
}
?>
But this code displays All of Custom Fields of post,
Is there a way to just display my own added Custom Fields?
All post_meta fields are saved into the Database with the same structure. If you need to loop a specific subset of meta, you can give them a similar name structure so you can filter them.
For example, if you give all your custom meta a name starting with 'my_custom_meta_' the code would be:
<?php
$meta = get_post_meta($post->ID);
foreach($meta as $key=>$val) {
if(preg_match('/^my_custom_meta_.+/', $key)) {
echo '<li><span>' . $key . ' : </span>' . $val[0] . '</li>';
}
}
?>
I have a case where I am using the code below to populate a template of sorts. Within the templates' javascript I would individually check the data attribute field I setup, essentially causing me to have multiple JS files instead of one that is shared. I then thought I could use a generic name field too, but prepend a number through the loop.
For example, with the line of code below where the `name="testField". I want to see if there is a way that I can add a number, but auto increment it through the loop with php.
Is this possible?
echo '<div class="markerItem" name="testField' . $number . '" "data-marker="' . $marker_data . '">';
PHP Code
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $key=>$marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" name="testField_'.$key.'" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
Using this, $key is assigned from the array index which will be a number starting from 0 and ending at count($marker_rows)-1.
Suprisingly, I couldn't find an appropriate duplicate for this.
You can easily increment or decrement variables in PHP.
$number = 0;
foreach ($marker_rows as $marker_row) {
...
$number++; // $number will now be $number+1
}
You can use $number++ directly in your attribute (if concatenating) as this will return the current $number then increment the value.
My question might seem totally silly but I am really stuck here.
I know $_SESSION is a global variable but I can't seem to know how to retrieve the value it stores.
For example:
<?php
if(isset($_SESSION["cart_products"]))
{
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_code = $cart_itm["product_code"];
echo '<p>'.$product_name.'</p>';
echo '<p><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></p>';
}
}
echo $_SESSION["cart_products"];
?>
Here you can see, the $_SESSION["cart_products"] holds some value (information like product name, product code etc). Now, the problem is that I just want to echo out all the product names that are stored in $_SESSION["cart_products"].
Since it's a cart list, it contains more than ONE product details. But, when I echo out $product_name, it only shows the name of the last product in the list. And echoing out $_SESSION["cart_products"] gives array to string error.
Please, tell me how can I list out all the product names separating by a ,.
Any help will be greatly appreciated.
Thanks in advanced.
PS: I have already tried using implode() function.
for displaying all the product name separated by , use this code.
$allProductName = '';
$prefix = '';
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$allProductName .= $prefix . '"' . $product_name. '"';
$prefix = ', ';
}
echo $allProductName;
Here's a edited version of your code
<?php
//you need to start session first
session_start();
$item = ["product_name" => "BMW", "product_code" => "540M"];
$list = array( $item, $item );
// Assuming you session list
$_SESSION[ "cart_products" ] = $list;
if(isset( $_SESSION["cart_products"])) {
foreach ( $_SESSION["cart_products"] as $cart_itm ) {
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_code = $cart_itm["product_code"];
echo '<p>'.$product_name.'</p>';
echo '<p><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></p>';
}
// to print names seperated by ','
$temp = "";
foreach ( $_SESSION["cart_products"] as $cart_itm ) {
$temp .= $cart_itm["product_name"] . ", ";
}
echo $temp;
}
// you cant print array using echo directly
print_r( $_SESSION["cart_products"] );
?>
Finally, I got the answer to my query with the help of #Christophe Ferreboeuf. However, some modification was still needed.
Here's the corrected code:
$allProductName = '';
$prefix = '';
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$allProductName .= $prefix . '"' . $cart_itm["product_name"]. '"';
$prefix = ', ';
}
echo $allProductName;
First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);