How to display currency in Indian numbering format in wordpress? - wordpress

One of my client have real estate website to sell properties. It was built in wordpress using houzez theme. That website have default numbering system where the separator shows at every three characters eg: 10 lacks : 1,000,000 , but in indian currency format it should be like : 10,00,000 .
The Indian currency numbering system is looks like :
1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
How do i change that numbering system in my wordpress website?
is there any plugin available?

Well, you can use the function numberToCurrencymade by hitswa
Then this function can be used in different ways:
Directly to the field: <?php echo numberToCurrency( get_post_meta( get_the_id(), 'price', true ) ); ?>
Apply a filter to the field assuming that your code to display the field is like this:
$unformatted_price = get_post_meta(get_the_id(), 'price', true);<br>
echo apply_filters('price_meta_content', $unformatted_price );
And on your functions.php <?php add_filter( 'price_meta_content', 'numberToCurrency' ) ; ?>
Another solution would be to add a filter to the_content
add_filter('the_content','strnumtocurrency', 99);
function strnumtocurrency($content){
$pattern = "/(\d+.\d+)/";
return preg_replace( $pattern, numberToCurrency('$1'), $content );
}
Here is the numberToCurrency code
<?php
function numberToCurrency($number)
{
if(setlocale(LC_MONETARY, 'en_IN'))
return money_format('%.0n', $number);
else {
$explrestunits = "" ;
$number = explode('.', $number);
$num = $number[0];
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
// creates each of the 2's group and adds a comma to the end
if($i==0)
{
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
if(!empty($number[1])) {
if(strlen($number[1]) == 1) {
return '₹ ' .$thecash . '.' . $number[1] . '0';
} else if(strlen($number[1]) == 2){
return '₹ ' .$thecash . '.' . $number[1];
} else {
return 'cannot handle decimal values more than two digits...';
}
} else {
return '₹ ' .$thecash.'.00';
}
}
}
?>

Related

Wordpress CF7 generate random unique string for each submision

So I`m trying to generate a dynamic hidden text field that will have a random string of letters and numbers into Contact Form 7.
I have tried the following code
add_action('wpcf7_init', 'custom_code_generator');
function custom_code_generator(){
wpcf7_add_form_tag('coupon_code', 'custom_code_handler');
}
function custom_code_handler($tag){
$input_code_name = 'rand_string';
$charsList = '1234567890abcdefghijklmnopqrstuvwxyz';
$randomString = '';
for ($i=4; $i < 10; $i++){
$randomString .= $charsList[rand(0, strlen($charsList))];
}
$finalCode = strtoupper($randomString);
$html = '<input type="hidden" name="'.$input_code_name.' "value=" '.$finalCode . ' " />';
return $html;
}
Based on this method
https://www.wpguru.com.au/generate-dynamic-tag-contact-form-7/
However it does not seem to work for me, I added the code to functions and tried a bunch of editing to it with no definitive results.
Main idea is that I need a unique string of characters for each CF7 submission, all submissions are stored into Wordpress and also a copy of the data is sent to another DB.
Adding the shortcode [coupon_code] to mail template returns nothing and no data seems to get stored trough the field at all.
What you have should essentially work. I made some tweaks and optimized some of your code by removing some extraneous declarations and there were also extra spaces around the values.
add_action( 'wpcf7_init', 'custom_code_generator' );
function custom_code_generator() {
wpcf7_add_form_tag( 'coupon_code', 'custom_code_handler' );
}
function custom_code_handler() {
$characters = '1234567890abcdefghijklmnopqrstuvwxyz';
$random_string = '';
for ( $i = 4; $i < 10; $i++ ) {
$random_string .= $characters[ wp_rand( 0, strlen( $characters ) ) ];
}
return '<input type="hidden" name="rand_string" value="' . strtoupper( $random_string ) . '" />';
}

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.

How to loop through numbers, when one of the fields numbers are constructed differently?

I have a bunch of custom fields on one of my post types, that is displayed randomly but in a fixed order. The names of the custom fields are always the same, and for every loop there is an increasing counter added to the custom field names.
Like this:
custom_text
custom_text1
custom_text2
custom_image
custom_image1
custom_image2
custom_video
custom_video1
custom_video2
The problem is, there is one field that begins with the number one, like this:
custom_special1
custom_special2
custom_special3
Right now, it's impossible to change this behaviour. Problem is, this makes the custom_special fields show up in the wrong place of the output, the first one shows up together with the fields with the number 1 at then end, instead of with the empty ones.
I need to tweak the code below with some kind of if statement, that says something like:
if $custom_special . $counter {output the result one step down}
The important thing is that it has to show up in between the other fields, so I can't have a separate function for the special field.
Here's my code, I hope some of you gurus out there can help me with a solution!
// max custom field index
$number = 40;
// the counter
$counter = '';
// the meta keys to check for
$keys = array(
'custom_text',
'custom_image',
'custom_video'
);
// all our custom field values
$custom_fields = get_post_custom( get_the_ID() );
// loop over our counter
while( $counter < $number ){
// loop over each of the keys
foreach( $keys as $key ){
// check if a custom field with key + counter exists
if( isset( $custom_fields[ $key . $counter ] ) ){
// output the field
// values will be in an array, 0 is the first index.
// you can loop over these as well if you have multiple values.
if (strpos($key, 'custom_text') !== false) {
$first = '<h2>';
$second = '</h2>';
echo $first . $custom_fields[ $key . $counter ][0] . $second;
}
if (strpos($key, 'custom_image') !== false) {
$first = '<img src="';
$second = '">';
echo $first . $custom_fields[ $key . $counter ][0] . $second;
}
if (strpos($key, 'custom_video') !== false) {
$first = '<p>';
$second = '</p>';
echo $first . $custom_fields[ $key . $counter ][0] . $second;
}
}
}
// increment the counter
$counter++;
}
I have thought about some different solutions, but still haven't been able to find one. My first idea is some kind of if statement, and the other one is to strip the numbers from the special field before the loop, and then rebuild it the way the other ones are constructed.
Still haven't been able to successfully create this though.
I hope that someone out there have a suggestion! Thanks a lot!
// Jens.
when you want to acecess this
custom_special1
custom_special2
custom_special3
using same counter you have for others you can simple do :
$counter2 = $counter+1;
$custom_fields[ $key . $counter2 ]
so for custom_special1 , you use $counter2 witch is $counter added 1 value.
Just a quick fix code ideea

Wordpress nextpage display Previous 2 of 10 Next

I'm using wp_link_pages() to split my post into multiple pages. I want to achieve something like this as shown in the image below. Instead of showing all the page numbers with links, I want it to show only this format (Current Page of Total Page). Please help me with the exact codes. Thank you so much in advance.
PS: I don't want to use plugins.
There is a simple solution to this problem. I've got this inspiration from source file where function wp_link_pages is defined.
function page_pagination( $echo = 1 )
{
global $page, $numpages, $multipage, $more;
if( $multipage ) { //probably you should add && $more to this condition.
$next_text = "next";
$prev_text = "prev";
if( $page < $numpages ) {
$next = _wp_link_page( $i = $page + 1 );
$next_link = $next . $next_text . "</a>";
}
if( $i = ( $page - 1 ) ) {
$prev = _wp_link_page( $i );
$prev_link = $prev . $prev_text . "</a>";
}
$output =
"<div class=\"prev-next-page\">"
. $prev_link
. "<span class=\"page-counter\">{$page} of {$numpages}</span>"
. $next_link
. "</div>";
}
if( $echo ){
echo $output;
}
return $output;
}
If you need more freedom you can always adapt this function to suit your purposes. Include function into wordpress loop! Like this for example:
if ( have_posts( ) ) {
while ( have_posts( ) ) {
the_post( );
//rest of code
the_content();
page_pagination();
}
}
As you can see, there is "private" function _wp_link_page used to solve your problem. I don't like using "private" functions, but it solves our problem.

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

Resources