Manipulate last iteration of foreach inside foreach - wordpress

I've created an array from three variables I get through a foreach loop.
//loop through each post
foreach($loop as $p){
//get the meta and taxonomy data
$term_list = get_the_term_list($p, "mountains",true);
$name = trim($term_list, "1");
$wtr_long = get_post_meta($p,"wtr_longitude",true);
$wtr_lat = get_post_meta($p,"wtr_latitude",true);
//Add to Array
$map_array[] = array ($name => $wtr_lat . "|" . $wtr_long);
}
Now this array should then deliver the data that will populate my Google Map, for that I'm using below code.
foreach( $map_array as $a){
foreach ($a as $key => $value) {
$pieces = explode("|", $value);
$trimmed_key = trim($key, "1");
$name = trim($trimmed_key);
?>
{latitude: <?php echo $pieces[0]; ?>,
longitude: <?php echo $pieces[1]; ?>,
html: <?php echo $name; ?>},
<?php }} ?>
This works almost fine (although it's probably not the cleanest code, tips on this would be appreciated too). The issue I'm having is that in the last iteration of the foreach inside the other foreach, I need to add a ], resulting in:
html: <?php echo $name; ?>}],
I can escape a single foreach, but doing it on a foreach inside a foreach is driving me insane. Any help would be greatly appreciated.

I'm not a php develeopor but you may want to build the collection of strings you want to echo first. After the collection is complete you can add the ']' the the last element. Then echo each element in your collection of strings.

atbyrd, your approach gave me a couple new issues, but did in the end lead to a working solution. Thank you for that.
Below the code that fixed the issue, hope it'll be helpful to someone else in the future.
//Add to Array
$map_string .= '{latitude: "' . $wtr_lat . '", longitude: "' . $wtr_long . '", html: "' . $name .'"},~!~';
//$map_string .= '{latitude: "' . $wtr_lat . '", longitude: "' . $wtr_long . '", html: "name"},~!~';
}
//Remove last three "~!~" characters from the string not to have one too many arrays when exploding
$clean_map_string = substr($map_string, 0, -3);
//Now I can explore on ~!~ to get a new array with the correct strings
$map_array = explode('~!~', $clean_map_string);
$i = 0;
$length = count($map_array)-1;
//Inserts all the markers
foreach($map_array as $value){
if( $i != $length ){
echo $value;
}
else {
echo str_replace("},", "}],", $value);
}
$i++;

Related

How display the spell out of an amount with currency details in WooCommerce

I am trying to spell out WooCommerce order total amount, in my invoice.php template file can reach order total amount.
First I tried:
$total = $order->get_total();
<?php echo ( $total ); ?> -
<?php
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format($total); ?>
The order total displayed is 225.00 and the spell out display is: two hundred twenty-five
Edit:
I found the following solution:
<?php $number = $order->get_total() ;
$formatter = new NumberFormatter('tr', NumberFormatter::SPELLOUT);
$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");
echo $formatter->format($number); ?>
But the result shows like that: two hundred twenty-five
The desired display should be: two hundred twenty-five turkish liras , zero penny.
How can i do this ?
The NumberFormatter SPELLOUT constant doesn't handle the decimals.
You can use the following custom function to display a float number amount spell out like (with the currency details):
function wc_spellout_amount( $amount, $country_code = 'tr' ) {
$formatter = new NumberFormatter($country_code, NumberFormatter::SPELLOUT);
$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");
$amounts = explode('.', (string) $amount); // Separating decimals from amount
$output = $formatter->format($amounts[0]);
$output .= ' ' . _n('turkish lira', 'turkish liras', $amounts[0], 'woocommerce');
$output .= ', ' . $formatter->format($amounts[1]);
$output .= ' ' . _n('penny', 'pennies', ( $amounts[1] > 0 ? $amounts[1] : 1 ), 'woocommerce');
return $output;
}
Code goes in functions.php file of the active child theme (or active theme).
Usage: Then you will use it as follows in your code:
echo wc_spellout_amount( $order->get_total() );
Tested and works.

I need to know if it's possible how to get_the_tags to array?

I need to know if it's possible how to get_the_tags() to array?
i want to like this
$myarray = array('one', 'two', 'three', 'four', 'five', 'six');
i want use this code with "replace the_content" like this
<?php
function replace_content($content){
foreach(get_the_tags() as $tag) {
$out .= $tag->name .',';
$csv_tags .= '"' . $tag->name . '"';
}
$find = array($out);
$replace = array($csv_tags);
$content = str_replace($find, $replace, $content);
return $content;
}
add_filter('the_content', 'replace_content');
?>
find tag in content and replace with link
$posttags = get_the_tags();
$my_array = array();
if ($posttags) {
foreach($posttags as $tag) {
$my_array[] = $tag->name ;
}
.. and if your final goal is to output it like you wrote above then :
echo implode(',', $my_array);
.. and by the type of question , I was not sure if by one,two.. you might be meaning ID , so :
$posttags = get_the_tags();
$my_array = array();
if ($posttags) {
foreach($posttags as $tag) {
$my_array[] = $tag->term_id ;
}
BTW - a quick look at the codex would have shown you that ...
You should be able to do something like this:
global $wpdb;
// get all term names in an indexed array
$array = $wpdb->get_results("SELECT name FROM wp_terms", ARRAY_N);
// walk over the array, use a anonymous function as callback
array_walk($array, function(&$item, $key) { $item = "'".$item[0]."'"; });
Notice that anonymous functions are only available since PHP 5.3
You should be able to do the same thing using get_the_tags() if you only want tags for a specific post:
$tags = get_the_tags();
array_walk($tags, function(&$item, $key) { $item = "'".$item->name."'"; });
Judging from your updated question you don't need any of the above code, the only thing you need to to in order to get single quotes around each tag is:
foreach(get_the_tags() as $tag) {
$out .= $tag->name . ',';
$csv_tags .= '"' . "'".$tag->name."'" . '"';
}

Drupal - Show child terms of current term, only if child items exist - code modification needed

Having fought with the problem of showing child terms for a given taxonomy term in a block, I finally stumbled on a piece of code that does exactly what I want here
As per the instructions I've added the following to my template.php
function themename_child_terms($vid = 1) {
if(arg(0) == 'taxonomy' && arg(1) == 'term') {
$children = taxonomy_get_children(arg(2), $vid);
if(!$children) {
$custom_parent = taxonomy_get_parents(arg(2));
$parent_tree = array();
foreach ($custom_parent as $custom_child => $key) {
$parent_tree = taxonomy_get_tree($vid, $key->tid);
}
$children = $parent_tree;
}
$output = '<ul>';
foreach ($children as $term) {
$output .= '<li>';
$output .= l($term->name, 'taxonomy/term/' . $term->tid);
$output .= '</li>';
}
$output .= '</ul>';
return $output;
}
}
I've then created a block and added :
<?php // $vid is the vocabulary id.
print themename_child_terms($vid = 1);
?>
This shows the child terms of the current term perfectly. However, it shows ALL terms that exist under the parent term, even if there is no piece of content using that term.
e.g.
viewing the page with all items in Term 1, I get
child 1
child 2
child 3
correctly listed in the block. But, if there are no pieces of content tagged with 'child 3' for example, it's still showing up that term in the block. This isn't very useful as it links to an empty term page.
How would I modify the code to only show children that actually have items associated with them. So if there are no children tagged 'Child 3', then that term would not show up. Is it an easy modification?
Thank you kindly for any solutions.
Nick
Working with Drupal 6
Thanks to user jerdiggity for posting the following reply over on drupal.stackexchange here. Works perfectly.
Hmm... I'd try something like this:
Change this part of your code:
foreach ($children as $term) {
$output .= '<li>';
$output .= l($term->name, 'taxonomy/term/' . $term->tid);
$output .= '</li>';
}
to something like this:
// Avoid unnecessary "Invalid foreach" errors showing up in the log:
if (!empty($children)) {
// If not empty, run the foreach loop:
foreach ($children as $term) {
// Then check to see if any nodes exist for that term id:
$number_of_nodes = taxonomy_term_count_nodes($term->tid);
// If there ARE nodes...
if ($number_of_nodes > 0) {
// ... then add them to the output:
$output .= '<li>';
$output .= l($term->name, 'taxonomy/term/' . $term->tid);
$output .= '</li>';
}
}
}
Hope that helps... :)

How to display WordPress RSS feed your website?

Hello i have a website and a blog, i want to display my self hosted wordpress blog on my website.
I want to show only 3 post on my website.
I want to automatically check for any new post everytime when i reload my website, so that the recent three gets displayed only.
I want to show the complete title of my wordpress blogpost but specific letters of description.
Also the description should end up with a word not some piece of non-dictionary word ending with "..."
How this can be done, i have heard that it can be done through RSS.
Can somebody help me?
To accomplish this you need to read the RSS of the blog, from RSS you need to read the Title and the description, after reading the whole description and title you need to trim the description to your desired number of letters. After that you need to check weather the description last word has been completed or not and then you need to remove a the last word if not completed and put the "...".
First we will make a script to trim the description and to put "..." in last:-
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
Now we will define the variables in which we store the values:-
$xml=("http://your-blog-path/rss/");
global $item_title, $item_link, $item_description;
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$x=$xmlDoc->getElementsByTagName('item');
Now, we will make an array and store values in it. I am only taking 3 because you have asked it the way. You can change it to anything (The number of post you want to show, put that in the loop)
for ($i=0; $i<3; $i++)
{
$item_title[$i] = $x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
$item_link[$i] = $x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
$item_description[$i] = $x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
}
?>
Now echo all these values, Link is the value where your user will click and he will be taken to your blog:-
FIRST RECENT POST:
<?php echo $item_title[0]; ?>
<?php echo substrwords($item_description[0],70); ?>
SECOND RECENT POST:
<?php echo $item_title[1]; ?>
<?php echo substrwords($item_description[1],70); ?>
THIRD RECENT POST:
<?php echo $item_title[2]; ?>
<?php echo substrwords($item_description[2],70); ?>
Hope this can solve your problem. By the way Nice question.
Click here for the original documentation on displaying RSS feeds with PHP.
Django Anonymous's substrwords function is being used to trim the description and to insert the ... at the end of the description if the it passes the $maxchar value.
Full Code:
blog.php
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
} else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
} else {
$output = $text;
}
return $output;
}
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/'); // <-- Change feed to your site
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 3; // <-- Change the number of posts shown
for ($x=0; $x<$limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$description = substrwords($description, 100);
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong>'.$title.'</strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>
You can easily put this in a separate PHP file (blog.php) and call it inside your actual page.
Example:
social.php
<h3>Latest blog post:</h3>
<?php require 'blog.php' ?>
Also, this code is plug-n-play friendly.
Why not use the Wordpress REST API to retrieve posts -
API URL is : https://public-api.wordpress.com/rest/v1/sites/$site/posts/
where $site is the site id of your wordpress blog
or else simply use this plugin -
http://www.codehandling.com/2013/07/wordpress-feeds-on-your-website-with.html

how to remove read more when full text is on in wordpress?

the code looks like this
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
there is an option in wp-admin>settings>reading>For each article in a feed, show
if this is set to full text
the excerpt() must return full length article instead of specified length.
how to do this?
Good question! The answer is simple: write your own function!
Open up functions.php in your favorite editor and mash random buttons on your keyboard until you get something like this:
function my_awesome_excerpt ($post_id = false, $full = false, $length = 22) {
if (!$post_id) global $post;
else $post = get_post($post_id);
$text = $post->post_content;
if ($full) return $text;
else {
$text_array = explode(' ', $text);
$return_string = array();
for ($i = 0; $i <= $length; $i++)
array_push($return_string, $text_array[$i]);
$new_awesome_string = '<p>';
$new_awesome_string .= implode(' ', $return_string);
$new_awesome_string .= '</p><p class="readmore">';
$new_awesome_string .= '<a href="' . get_permalink($post_id) . '">';
$new_awesome_string .= 'Read More' . '</a></p>';
return $new_awesome_string;
}
}
Now, you're ready for the cool part. Once you're in your loop, you can write out some magic like this:
echo my_awesome_excerpt();
and it will automagically spit out an excerpt. It's using the global post variable and everything! You can even use it outside of the loop:
echo my_awesome_excerpt($cpt->ID, 22);
and set your own special length!
Or maybe you just know in your heart that it's not worth it, you just want to show the whole thing. How's that look?
Inside the loop, you're going to have to give it a post ID, sorry about that.
echo my_awesome_script($post->ID, false);
I hope this helps. Have a great day!

Resources