WordPress Custom Field conditional based on postmeta value - php

I've got a chunk of code that's working fine, but I need to alter it.
It works but only if there's a value in the DB. If not, it produces a value of 0.0 which is ok...but I want it to say "N/A" as opposed to 0.0.
How would I alter the following block of code so it would display a value of "N/A" if the value was 0.0 and otherwise function as it already does?
<?php
global $wp_query;
$postid = $wp_query->post->ID;
if( get_post_meta($postid, 'Rankextras', true)) {
echo '<span class="skill-bg" data-percent=" ' . get_post_meta($postid, 'Rankextras', true) . '%" style="width: ' . get_post_meta($postid, 'Rankextras', true) . '%"> </span><span class="skill-name"> Extras</span><span class="skill-progress">' . get_post_meta($postid, 'Rankextras', true) . '</span>';
}
?>

Wordpress is already going to return an empty string if the metadata does not exist. Based on the code that you posted, could it be that there is some javascript that formats empty data-percent attributes to be 0.0?

Try this (modify the block where it echos 'N/A' to your needs):
global $wp_query;
$postid = $wp_query->post->ID;
$value = get_post_meta($postid, 'Rankextras', true);
if(!$value OR $value == '0.0')
{
echo 'N/A';
}
else
{
echo '<span class="skill-bg" data-percent=" ' . $value . '%" style="width: ' . $value . '%"> </span><span class="skill-name"> Extras</span><span class="skill-progress">' . $value . '</span>';
}
I also refactored your code a bit, so it uses less queries.

Related

If Else On Php Wordpress

<?php
$genre = get_the_term_list($post->ID, 'genre', '<span class="genre">', ', ', '</span>');
$tags = get_the_term_list($post->ID, 'tag-series-movies','<span class="genre">', ', ', '</span>');
if($genre,$tags)
echo '<li>Genre: '. $genre . '</li>';
echo '<li>Tags: '. $genre . '</li>';
else {
echo '';
}
?>
Hi. Guys whats wrong of my code? though the code is working 50%. the $genre is working but the else is not working. please help. i want to show the nothing when no genres is not available.
Change if($genre == $genre) to if($genre){
get_the_term_list returns the list or false so you just need to check that $genre is a truthy value
In your current code when $genre is false you are checking if(false == false) which always returns true
EDIT:
you can simplify your code like this
if($genre){
echo '<li>Genre: '. $genre . '</li>';
}
if($tags){
echo '<li>Tags: '. $tags . '</li>';
}
There's no need for the else statement as you're not echoing anything

PHP -displaying 12 items of an associative array with specific key and value

<?php
foreach($catalog as $id=> $item) {
echo get_item_html($id,$item);
}
// here is the functions page code :
function get_item_html($id,$item){
$output = "<li><a href='#'><img src='"
. $item["img"] . "' alt='"
. $item["title"] . "' />"
. "<p>View Details</p>"
. "</a></li>";
return $output;
}
?>
I have used it for displaying product categories i checked several time but I did find any error but it display undefined variable
please help me to find out this solution

Insert html into PHP return

My PHP is failing me. I'm trying to put a div around an element in a function. Here is the original code:
if ($withCurrency) {
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
return $currency . ' ' . $lowestPrice;
}
I want to put a div around the $currency.
I've tried changing this line:
return $currency . ' ' . $lowestPrice;
to this:
return "<div>" . $currency . "</div> " . $lowestPrice;
However that actually outputs the div tags as text on the page. Can someone tell me how to add the divs so they render as html?
UPDATE:
Here is the entire function:
function getTourPrice($tourId, $withCurrency = true) {
$lowestPrice = false;
$offers = getTourOffers($tourId);
// first get price from special offers
foreach ($offers as $offer) {
if ((isset($offer->options['special'])) && ((!$lowestPrice) || floatval($offer->options['price']) < $lowestPrice)) {
$lowestPrice = floatval($offer->options['price']);
}
}
// if special price isn't available then get price from normal offers
if (!$lowestPrice) {
foreach ($offers as $offer) {
if ((!$lowestPrice) || (floatval($offer->options['price']) < $lowestPrice)) {
$lowestPrice = floatval($offer->options['price']);
}
}
}
if (!$lowestPrice) return false;
if ($withCurrency) {
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
return $currency . ' ' . $lowestPrice;
} else {
return $lowestPrice;
}
}
The result of that function is called with the following code:
{var $lp = getTourPrice($post->id)}
{if $lp}<div class="item-price"><span><span><span class="from">From</span>{$lp}</span></span></div>{/if}
If I use echo instead of return like this:
echo "<div>" . $currency . "</div> " . $lowestPrice;
I lose all the html above. I.E. What was the following:
<div class="item-price"><span><span><span class="from">From</span>{$lp}</span></span></div>
Becomes this:
<div>R</div> 56200
(where R is $currency and 56200 is $lowestPrice)
Hope that's not painfully convoluted.
This will have something to do with what you are doing with the return
I imagine if you did this:
if ($withCurrency) {
$currency =
(isset($GLOBALS['aitThemeOptions']->directory->currency)) ?
$GLOBALS['aitThemeOptions']->directory->currency :
'';
echo "<div>" . $currency . "</div> ";
}
It would work.
Is your code the end of a function?
Try using the :
{$lp|escape:false}
I would simply place the div in the $currency variable, so it will be added upon return. I would change this line of code:
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
to this:
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? '<div>'.$GLOBALS['aitThemeOptions']->directory->currency.'</div>' : '';
or another method:
$currency = '<div>'.$currency.'</div>';
This way you are defining the html in the variable and not in the return. This is not tested, but it is the way I tend to code. :) Hope it helps!
Also one more thing, it is a bit of controversy among programmers, but I also recommend using single quotes when defining html in php.

PHP/WordPress: override page_id in foreach loop

I have a WordPress site and currently the code it set to create titles based on the page title. The titles are: Interior House Painting, Exterior House Painting and Commercial Painting. I would like to override the titles to remove the word "house". This is the code currently:
<?php
// interior_painting: 18
// exterior_painting: 25
// other services: 36
$page_ids = array(18, 25, 36);
$images = array('servicesInterior.jpg', 'servicesExterior.jpg', 'servicesOther.jpg');
foreach ($page_ids as $key => $page_id) {
$page_post = get_post($page_id);
$page_custom_key = 'home_page_info';
$page_link = $page_post->post_name;
$li_class = $page_id == 36 ? 'noMargin' : '';
$title = $page_id == 18 ? 'Interior Painting' : $page_post->post_title . " ";
$title = $page_id == 36 ? 'Commercial Projects' : $page_post->post_title . " ";
$title = $page_id == 25 ? 'Exterior Painting' : $page_post->post_title . " ";
echo '<li class="' . $li_class . '"> <a href="' . $page_link . '">';
echo '<img class="alignright size-full wp-image-349" title="servicesInterior" src="/wp-content/uploads/2011/04/' . $images[$key] . '" alt="" width="200" height="95" /></a>';
echo '<h2>' . $title . '</h2>';
echo get_post_meta($page_id, $page_custom_key, true);
echo '<a class="btn-find-more" href="' . $page_post->post_name . '">FIND OUT MORE</a></li>';
}
?>
The output is this: Interior House Painting, Exterior Painting, Commercial Painting. How do I get "house" removed from "Interior House Painting"?
$title = ucwords(trim(strtolower(str_replace('house', '', $page_post->post_title))));
Though, I am a little curious as to why you would not prefer to just remove the word from the title altogether.
ADDITIONALLY: Somebody else mentioned using preg_replace. That's also entirely possible, but it would be best to do a case-insensitive search:
$title = trim(preg_replace('/house/i', '', $page_post->post_title));
Just use preg_replace('House'|| 'house','',/*Variable Page title is in*/);
You could try replacing the line:
echo '<h2>' . $title . '</h2>';
With something like this:
if (is_page('Interior House Painting')) { echo '<h2>Interior Painting</h2>'; }
if (is_page('Exterior House Painting')) { echo '<h2>Exterior Painting</h2>'; }
else { echo '<h2>' . $title. '</h2>'; }

PHP looping problem?

I'm trying to display the first row in one color and the second row in another color but my code displays the result twice in both colors for example lets say I have 5 results my code will double the results by displaying 10 results. How can I fix this problem?
Here is the php code.
while ($row = mysqli_fetch_assoc($dbc)) {
//first row
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
//second row
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
You need to change the class on each row:
$count = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if( $count % 2 == 0 ) {
$classMod = '';
} else {
$classMod = '-2';
}
//first row
echo '<h3 class="title' . $classMod . '">' . $row['title'] .'</h3>';
echo '<div class="summary' . $classMod . '">' . substr($row['content'],0,255) . '</div>';
$count++;
}
your code should be like this
CSS
.odd { background: #CCC }
.event { background: #666 }
PHP
$c = true;
while ($row = mysqli_fetch_assoc($dbc)) {
$style = (($c = !$c)?' odd':' even');
echo '<h3 class="title '.$style.'">' . $row['title'] .'</h3>';
echo '<div class="summary '.$style.'">' .substr($row['content'],0,255) . '</div>';
}
Here's a solution with minimal repetition:
$count = 0;
while (($row = mysqli_fetch_assoc($dbc)) && ++$count) {
printf(
'<h3 class="title%1$s">%2$s</h3>'
. '<div class="summary%1$s">%3$s</div>'
, $count % 2 ? "" : "-2"
, $row['title'] // might want to use htmlentities() here...
, substr($row['content'], 0, 255) // and here...
);
}
$i = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
$color =$i % 2;
echo '<h3 class="title-' .$color . '">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
$i++;
}
Your code just displays every result twice. Use a conditional (e.g. an integer or a boolean) to switch between rows (like: if true, then green; if false, then red).
For a boolean you could change the current value like so:
bool = !bool;
Couple of extra points:
You don't (normally) need so many classes. If you have <div class="stripe"> as your container, you can target the items with e.g. .stripe h3 in CSS.
If you target the odd and even items in CSS with .stripe h3, you can then overwrite just the odd items.
In a perfect world, you should keep presentation in the CSS. All browsers but IE7 and below support div:odd to target any odd child of a parent. This may require changing the structure of your HTML slightly. For IE7 and below, I'd add classes with JavaScript instead of PHP. When IE7 is no more then you can just remove the JS.
By the way, you could do this code too:
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<h3 class="title">' . $row['title'] .'</h3>';
echo '<div class="summary">' . substr($row['content'],0,255) . '</div>';
if($row = mysqli_fetch_assoc($dbc)){
echo '<h3 class="title-2">' . $row['title'] .'</h3>';
echo '<div class="summary-2">' . substr($row['content'],0,255) . '</div>';
}
}
IMO, there is no excuse for not delegating this kind of non-critical, presentation layer decoration to client side code.
Just use a library like jQuery and access the odd and even rows like so:
<script>
$(document).ready(function()
{
//for your table rows
$("tr:even").css("background-color", "#F4F4F0");
$("tr:odd").css("background-color", "#EFF1F2");
});
</script>
You'll have us generating font tags next.

Categories