Advanced Custom Fields and Commas in Numbers - php

I have ACF (Advanced Custom Fields) on my WordPress website and am trying to add a comma every 3rd place (1,000) instead of (1000) using PHP. I am utilizing the code below but when I save it the website breaks (critical error). I suspect this is my own error (novice) and hope someone can help me find out what I'm doing incorrectly or what I could try.
`
add_filter('acf/format_value/name=number_of_supporters', 'fix_number', 20, 3);
function fix_number($value, $post_id, $field) {
$value = number_format($value);
return $value;
}
`
The website URL is https://coregiving.org and it leverages the Oxygen builder (if it's relevant).
Thank you!
-I was expecting the code I added to my website would add a comma delimiter-

Assuming the ACF field type is number, ACF is going to return the raw number. Rather than trying to filter the value, you could instead use the number format function in the template where you are going to display it. Something like this:
echo number_format( get_field( 'number_of_supporters' ) );

Related

Why won't my substr call work with the → character?

I'm building a WooCommerce site for a client using WordPress at the moment and I've written a piece of code that dynamically generates tables with products and product attributes in them. When I call the get_title() method, it gives me a title with the product's parent product first, the "→" sign, then the actual title of the product. I wrote this code to remove the "→" sign and everything before it.
$name_raw = $product->get_title();
$name = substr($name_raw, ($pos = strpos($name_raw, '→')) !== false ? $pos + 1 : 0);
It used to work perfectly, but not anymore. This code also works perfectly with every other character I've put in to test it, but not with that stupid little arrow. It seems like a recent update to something I'm using must've removed this method's ability to handle non-conventional characters. Can anyone recommend any possible solutions?
Since it's a WP environment title, the right arrow character probably has been entered using the WP form for a post. I think this character would be converted to it's HTML code, one of these:
→
→
→
→
→
→
→
So I'd do something like this:
function no_right_arrow_name($name_raw) {
if (empty($name_raw))
return $name_raw;
$right_arrows = array(
'→',
'→',
'→',
'→',
'→',
'→',
'→'
);
$name_new = $name_raw;
// removes all possible combinations of right arrows
foreach ($right_arrows as $right_arrow)
$name_new = str_replace($right_arrow, '', $name_new);
return $name_new;
}
$name_raw = $product->get_title();
$name = no_right_arrow_name($name_raw);

WordPress PHP htmlspecialchars(get_field... cannot read arrays?

I am working on a WordPress Website/Blog with two main functions.
Create reports.
Compile final report.
People can write reports, selecting the fields they need and publish it. Then at the end of the day, they can "compile" a final report from all of the reports (it concatenate the fields of all reports).
The theme is twentyten (in case it might be useful).
In my function.php file, I concatenate everthing for the final report using a foreach and lines like that:
$Urgences_Environnementales .= htmlspecialchars("<br/>".get_field('Urgences_Environnementales', $idnumber->ID));
$avezvous_regardé_des_indices_de_temps_violent_aujourdhui .= htmlspecialchars(get_field('avezvous_regardé_des_indices_de_temps_violent_aujourdhui', $idnumber->ID));
$quelle_est_cette_raison .= htmlspecialchars(get_field('quelle_est_cette_raison', $idnumber->ID));
One line per field, all the same way. After the loop is done, I update the fields:
update_field('Urgences_Environnementales',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($Urgences_Environnementales)), $identificationRapport);
update_field('avezvous_regardé_des_indices_de_temps_violent_aujourdhui',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($avezvous_regardé_des_indices_de_temps_violent_aujourdhui)), $identificationRapport);
update_field('quelle_est_cette_raison',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($quelle_est_cette_raison)), $identificationRapport);
Then it's printed for the final report like this (this is a single field):
if(strip_tags(html_entity_decode(get_field('Urgences_Environnementales')))!=''){
simplebox(strip_tags(html_entity_decode(get_field('Urgences_Environnementales')))!='', get_field('Urgences_Environnementales'));
}
And for those fields it works perfectly.
My problem is that all my fields composed of arrays (checkboxes that people can select multiple choices using the ACF plugin) are empty in my databse... They appear perfectly in the single reports, but they appear blank in the final report.
As an exemple, this is what I see in my database for a single report for one of my arrays:
a:4:{i:0;s:49:"L’indice d’intensité d’orage violent (STI)";i:1;s:35:"L’indice d’orage violent (TMPV)";i:2;s:34:"Potential Severe Storm Environment";i:3;s:6:"Autres";}
The corresponding field in my final report is empty.
Would someone have an idea on how to read those arrays and record them correctly in my databse? Could I transform them in strings in my foreach loop? Should I do something differently?
If you need more code don't hesitate to ask. I didn't put all my 3 functions (functions.php, report.php, finalreport.php) that I have in my WordPress theme as it would take tons of lines and I'm pretty sure the most important ones are right here. If I'm wrong, I could post the functions.
I searched and searched, but I can't seem to find the answer by myself, so I'm searching for help here.
PS: This is my 1st post, if you have any reccomandations, you can send them to me and I will change my post.
Thank you very much for your help!
PPS: I'm sorry for my english, I'm french, from Montreal, Qc, Canada.
Advanced Custom Fields stores some values as serialized arrays (checkboxes, repeaters, etc). Your code is assuming that you will be getting a string back. As you suggested in your answer, the easiest way to account for this in your current code would be to use the is_array() method to check the type of the returned value, and then another inner loop to handle the summary. This code assumes you just want to concatenate all the values, you could just as easily use another array to make sure they are unique, etc.
// get the value from acf
$value = get_field( 'Urgences_Environnementales', $idnumber->ID );
// if it's already an array, use that, if not make it into an array with a single element
$value_arr = ( is_array( $value ) )? $value : array( $value );
$text = ""; // reset since this is in a loop
// concatenate each checkbox value
foreach ( $value_arr as $val ){
$text .= $val . ', ';
}
// append it to the main summary
$Urgences_Environnementales .= htmlspecialchars( "<br/>". $text );

PHP character encoding issue

When I grab the title from my Word Press posts in code and pass them around as email, the punctuation gets a bit mangled.
For example "TAMAGOTCHI P’S LOVE & MELODY SET" comes out as "TAMAGOTCHI P’S LOVE & MELODY SET".
Any ideas how I prevent this?
Let me know if you need to see the specific code I'm currently using. (I'm not really sure if this is a WordPress issue, or a PHP issue.
EDIT
What happens is that this title is passed to a form via the query string. Then when the form is submitted, I take the string from the form field and email it.
So I guess I need to decode the html either before I pass it into the form field, or else before I email it.
EDIT 2
Weird, so I looked closer at the code and I'm already doing a urldecode before I pass the value into the form field
jQuery('#product_name').val("<?php echo urldecode(strip_tags($_GET['pname'])); ?>
Is there some default encoding happening when you serialize (for ajax formhandler)
var dataString = $(this).serialize();
EDIT 3
OK turns out the code is more complex. Title is also passed to some kind of wordpress session before it's hits the form. I'll figure it out where exactly I need to put urldecode. Thanks!
This is one WordPress "feature" I could do without.
Here's one down-n-dirty method to get the fancy quotes (or other entities) replaced:
$title = get_the_title( get_the_ID() );
$title = str_replace( '&#8217', "'", $title );
echo $title;
We could integrate deeper, by hooking into the_title, if you want this same de-entities functionality throughout the site. This code block would belong in your theme's functions.php file.
function reform_title($title, $id) {
$title = str_replace( '&#8217', "'", $title );
return $title;
}
add_filter('the_title', 'reform_title', 10, 2);
Im not really sure about wordpress, but the issue itself its that the text its coming out as URLENCODE instead of a UTF-8 or other encode.
You have two options
When you receive the text you never turn it back to normal encoding (Which is weird as usually is de-encoded by php when you access the $_GET or $_POST variables)
You are parsing the message with the urlencode() function.

Tag Array Sorting issue

10/25/2012 - Still Not solved! Please see below:
My client has a WordPress Tag Cloud (tag array) with tags which include ["] character as well as [The] prefix for some tags. I.e:
"rose"
"autumn"
The Abby
The Cloud
The Elephant
Obviously all the tags enclosed in the quotations marks ["] are sorted on the top of the list and all the words starting with [The] prefix are sorted somewhere around the letter [T] (following the logical ASC order).
It was sprinkled on me that: "All tags (in the WP tag cloud) have to be ordered Ascending but those which contain the [" "] or [The] characters have to be sorted with all other tags in the chronological order, ignoring the ["] and [The] prefix.
I looked into the WP core function:
**function wp_generate_tag_cloud**
but I have no idea where to start. In the raw SQL statement, I could probably use the trim() to filter out the [" "] and [The] characters form the tag cloud array but that is only a thought which I have no idea how to apply.
wp_generate_tag_cloud() invokes a filter named tag_cloud_sort, which can override the sort order specified in the $args parameter. The tag_cloud_sort filter receives an array of tags and the actual $args parameter passed to wp_generate_tag_cloud(), so it can inspect the full settings of the wp_generate_tag_cloud() invocation and adjust its behavior accordingly.
You could try something like this:
function custom_tag_sort($tags, $args) {
if ($args['orderby'] != 'name') {
// do not reorder if sort order is not by name.
// wp_generate_tag_cloud() is smart enough to notice order
// is not changed and will proceed with its regular sort logic.
return $tags;
}
uasort($tags, 'custom_tag_sort_compare');
}
function custom_tag_sort_compare($a, $b) {
return strnatcasecmp(
custom_tag_sort_normalize($a->name),
custom_tag_sort_normalize($b->name)
);
}
function custom_tag_sort_normalize($tag) {
// strip quote marks
$tag = trim($tag, '"');
// strip leading definitive article
$tag = preg_replace('/^\s*the\s+/i', '', $tag);
return $tag;
}
add_filter('tag_cloud_sort', 'custom_tag_sort');
Disclaimer: I've written this after only a cursory inspection of the wp_generate_tag_cloud() function. I haven't tested it on a live WordPress installation; I have only verified that the sorting function works correctly on your sample tag cloud:
The Abby
"autumn"
The Cloud
The Elephant
"rose"
ok so you want to avoid modifying the core code of wordpress... when your client hits the update button after you told him not to, then your going to have to go in and mess with it again.. use action hooks instead. there is conveniently one for hooking into the output for the tag cloud function. add this to your themes functions file
function tagCloudFilter($tagCloudString, $args)
{
$tagCloudString = str_replace('The','', $tagCloudString);
$tagCloudString = str_replace('"','', $tagCloudString);
}
add_filter('wp_tag_cloud', 'tagCloudFilter', 10, 2);
That will atleast get rid of the stuff you dont want. as far as sorting it im not to sure but this should get you on your way. it may be easier to sort it with jquery
If you really want to modify the core code run a foreach loop in the tag array before its formatted and use the str_replaces from above in that loop.. The just run sort() on that array and you should be good. But if it were me i would go with the half solution and not have it alphabetized than to modify the wordpress core
Here's a thought:
you could copy the original tag_cloud function and create your own on your functions.php.
You make the changes you want to make and add this filter inside the function:
$return = apply_filters( 'YOUR_tag_cloud_function', $return, $args );
And then create the previous filter to add your function to the hook:
add_filter('wp_tag_cloud', 'YOUR_tag_cloud_function');
I don't know if it works, I didn't test it. What do you think?

Wordpress apply get_excerpt formatting to a string

I would like to apply wordpress' get_excerpt format to a string I pass to it.
I know the standard excerpt only works within the loop - but I'm hoping there is a function or something I'm missing that generates the excerpt when you don't manually define one.
Fixed answer:
You need wp_trim_words(). Yes - you're right. wp_trim_excerpt() doesn't play nice with passed strings.
http://codex.wordpress.org/Function_Reference/wp_trim_words
wp_trim_words( "I would like to apply wordpress' get_excerpt format to a string I pass to it. I know the standard excerpt only works within the loop - but I'm hoping there is a function or something I'm missing that generates the excerpt when you don't manually define one.", 5, '[...]' ); returns "I would like to apply[...]"
Previous answer:
WordPress uses wp_trim_excerpt() to generate excerpts.
http://codex.wordpress.org/Function_Reference/wp_trim_excerpt
You probably want some filtering on there too before you output (depending on the source of your text).

Categories