How to Display My Own Custom Fields on Wordpress Theme? - php

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>';
}
}
?>

Related

Grouping/Ordering Items in PHP Object Array

I have a sitemap that I'm trying to group by URL and stack them based on URL. Here is the sitemap https://www.sitecentre.com.au/sitemap
Basically, I need this to be dynamic. I can make this easily by doing a case, or if statements, like I've done on the Blog section, but I need it dynamic. It needs to look like this:
<li>Web Design
<ul>
<li>Nested in Web Design</li>
<li>Nested in Web Design</li>
</ul>
</li>
All based on the URL. the URL is /design then the nested would be design/nested
Then the next group would be like branding and nested on branding so it's all organised and laid out perfectly, then alphabetically ordered based on something else.
Here is our current PHP:
<?php
$pages = json_decode(file_get_contents('data/pages.json'));
foreach ($pages as $data){
foreach ($data as $key => $values){
if ($values->status === '1' && $values->visible === '1' && $values->slug !== 'home'){
if ($values->slug !== 'blog'){
echo '<li>' . $values->heading . ' - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '</li>';
} else {
// Get the latest blogs
$blogs = json_decode(file_get_contents('data/blogs.json'));
echo '<li>' . $values->heading . ' - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '';
echo '<ul>';
foreach ($blogs as $data){
foreach ($data as $key => $values){
if ($values->status === '1' && $values->visible === '1'){
echo '<li>' . $values->heading . ' - Last Updated: ' . date('d/m/Y', strtotime($values->date_modified)) . '</li>';
}
}
}
echo '</li></ul>';
}
}
}
}
?>
It clearly needs a bit of work in order to make this work, but I cannot for the life of me work out where to start.

Display multiple product custom fields within a loop in WooCommerce

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;

php - Retrieve value from $_SESSION and output using another variable

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;

Shop with two items

I have two models. Shop and Item. I am trying to retrieve all of the shops, with 2 items each - however, I cannot get it working. The value of $shop['items'] is not changing.
foreach($shops as &$shop) {
foreach($shop->items as $item) {
$item->formatPreview();
}
$shop = $shop->toArray();
$shop['items'] = array_slice($shop['items'], 2);
}
How can I achieve this, and are there a smarter way using Eloquent?
EDITED
$shops = Shop::with('items')->get();
foreach ($shops as $shop) {
echo 'shop name: '. $shop->name . '<br>';
if($shop->items()->count()) {
foreach ($shop->items()->take(2)->get() as $item) {
echo 'item: ' . $item->name . '<br>';
}
}
echo '<hr>';
}
I was testing this inside a route closure so please format it as you want orfourse. Hope it is working now.

mssql_fetch_array only displays one row if columns are put into variables

I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.

Categories