I'm trying to add regular expression validation to Contact Form 7 'last-name' field that will allow for hyphenated names. I have researched and written a function to allow for this, but it doesn't seemed to be working. Any help would be appreciated.
Here is the function I have written and placed in functions.php file...
add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2);
function custom_text_validation($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
if($name == 'last-name') {
$value = $_POST[$name];
if(!preg_match('[a-zA-Z\-]', $value)){
$result->invalidate($tag, "Invalid characters");
}
}
return $result;
}
So the first thing I think we will need to look at it is on your 5th and 6th lines. According to the CF7 documentation, the $tag argument actually returns an object and not an array.
Which means that $tag['name'] and $tag['type'] should actually be $tag->name and $tag->type.
The second thing to address is your regex expression, now would be a good time to read up on Falsehoods Programmers Believe about Names. Basically, in short, there are a lot of last names that will not match if the criteria is MixedAlpha and a dash.
If, however, you are intent on cutting out a portion of potential users, might I suggest making use maček's basic regex listed on this SO answer as it will atleast include a few more potential valid last names.
This would turn your function into something like this:
add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2);
function custom_text_validation($result, $tag) {
$type = $tag->type; //object instead of array
$name = $tag->name; //object instead of array
if($name == 'last-name') {
$value = $_POST[$name];
if(!preg_match("/^[a-z ,.'-]+$/i", $value )){ //new regex statement
$result->invalidate($tag, "Invalid characters");
}
}
return $result;
}
Try negating it
if(preg_match('/[^a-z\-]/i', $value)){
I've also updated it to use /i, which will ignore case
Related
I have posts with slugs with special characters. One of them is the following:
http://localhost/wp-json/wp/v2/posts?slug=my-post!
Unfortunately, WP REST API not showing the content since it has (!) within the slug.
Is there any solution you guys would recommend?
I have found the solution (at least for my case), not sure if it'll work for you but may indicate you the way to go. We need to tap into the function used to sanitize the slugs, as I said in my comment, by default is wp_parse_slug_list. Looking at the code the function that actually sanitizes the slug is sanitize_title.
Looking at the source code, wp_parse_slug_list calls sanitize_title with only one argument, which means that the context used is save. This means that, for posts that were already saved without being sanitized by this function, the slug won't match and the post will be inaccessible through the API. The solution is to change the sanitizing function slightly by adding a filter:
add_filter('rest_post_collection_params', function($query_params) {
$query_params['slug']['sanitize_callback'] = 'sanitize_rest_api_slug';
return $query_params;
}, 20, 1);
function sanitize_rest_api_slug( $list ) {
if ( ! is_array( $list ) ) {
$list = preg_split( '/[\s,]+/', $list );
}
foreach ( $list as $key => $value ) {
$list[ $key ] = sanitize_title( $value, '', 'query' );
}
return array_unique( $list );
}
The filter is actually being applied on the function get_collection_params() on the class-wp-rest-posts-controller class, but if you look at the source code, the filter has a variable depending on the post_type, so if you have another special kind of posts defined (besides post) you need to add/change a filter for that kind as well.
I hope this helps somebody else like me, even if it's too late for your issue.
Can Wordpress shortcodes have attributes without values like this?
[foo some_att]
I know it can be like this:
[foo some_att=""]
Can I have shortcode values like this (with curly braces)?
[foo path="{'quality': '720p', 'mp4': 'PATH_TO_MP4_VIDEO'}"]
You sure can! RichJenks has a short yet informative article on implementing this functionality, which boils down to defining a new function that can tell you if a flag (argument with no associated value) is present in your $atts array:
function is_flag( $flag, $atts ) {
foreach ( $atts as $key => $value )
if ( $value === $flag && is_int( $key ) ) return true;
return false;
}
After defining this function, you can reference is_flag() in your shortcode function to tell if the flag has been provided as part of the shortcode invocation:
if is_flag( 'some_att', $atts )
// flag is present
else
// flag is not present
Unfortunately, the example you've provided wouldn't work as an argument value with the Wordpress shortcode parser. According to the official Wordpress documentation on the Shortcode API:
Attribute values must never contain the following characters:
Square braces: [ ]
Quotes: " '
Since your example makes use of the single-quote character ('), it is officially unsupported by the shortcode parsing engine.
You can use this for first question.
is_int( array_search( 'some_att', $atts ?: [] ) )
I am trying to write a wordpress filter that would change the post status to trash if it contains explicit words, but I can't manage to get it to work. Could you please help me?
This is what I got so far:
add_filter('wp_insert_post_data', 'delete_invalid_posts', '99');
function delete_invalid_posts($data) {
$false_titles = array("*****", "******");
if (in_array($data['post_title'], $false_titles) {
// If post data is invalid then
$data['post_status'] = 'trash';
}
return $data;
}
If you want to search the title for Explicit Words, you may use this code:
add_filter('wp_insert_post_data', 'delete_invalid_posts', 99);
function delete_invalid_posts($data) {
$false_titles = array("*****", "******");
$title_arr = explode(' ', $data['post_title']);
$found = array_intersect($false_titles, $title_arr);
if (!empty($found)) {
$data['post_status'] = 'trash';
}
return $data;
}
I've not tested the code, So try it and if you have any question don't hesitate to ask.
I might be wrong, but I think you are missing a closing parentheses here...?
Are you getting an error message?
if (in_array($data['post_title'], $false_titles) // <--- HERE should be a ")"
Like I said, I could be mistaken or there may be other issues...
I am using the Postie plugin to auto post from email on my Wp blog.
I am trying to populate two custom fields (mail_meta_from and mail_meta_replyto") with the "from" and "reply to" fields
add_filter('postie_post_before', 'add_custom_field');
//Get the "from" and "replyto" email details
add_filter('postie_filter_email2', 'get_emaildetails', 10, 3);
function get_emaildetails( $from, $toEmail, $replytoEmail) {
DebugEcho("step-01b");
DebugDump("from " . $from);
DebugDump("toEmail " . $toEmail);
DebugDump("replytoEmail " . $replytoEmail);
$fromField = $from;
$replytoEmail = $replytoEmail;
return $from;
return $replytoEmail;
function add_custom_field($post) {
add_post_meta($post['ID'], 'mail_meta_from', '$from');
add_post_meta($post['ID'], 'mail_meta_replyto', $replytoEmail);
return $post;
}
}
This has been driving me nuts for the past 2 days, and I have tried multiple variations of the above but with no success.
At the moment, I am getting the error
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'add_custom_field' not found or invalid function name in /home/sites/mysite.com/public_html/wp-includes/plugin.php on line 213
I try and learn from my mistakes, but I am not getting anywhere with this...
The default answer for help with this on the WP forum is to check out http://postieplugin.com/extending/.
Which I have... repeatedly.
Any help would be greatly appreciated!
You are defining the add_custom_field() function inside the scope of the get_emaildetails() function because it is within the curly braces. You should also consider using a more unique name for your function, or encapsulate it an an object namespace. The error you are getting indicates that when the apply_filter() is called for postie_post_before it can't find a function called add_custom_field(). Use the code below to properly scope the function, though note that you have some other syntax errors as well.
add_filter('postie_post_before', 'add_custom_field');
function add_custom_field($post) {
// the variable $from is not defined, and it will not evaluate if enclosed
// in single quotes. if you want the value of $from define it then use "{$from}"
add_post_meta($post['ID'], 'mail_meta_from', '$from');
// $replytoEmail is not defined
add_post_meta($post['ID'], 'mail_meta_replyto', $replytoEmail);
return $post;
}
//Get the "from" and "replyto" email details
add_filter('postie_filter_email2', 'get_emaildetails', 10, 3);
function get_emaildetails( $from, $toEmail, $replytoEmail) {
DebugEcho("step-01b");
DebugDump("from " . $from);
DebugDump("toEmail " . $toEmail);
DebugDump("replytoEmail " . $replytoEmail);
// what is this for?
$fromField = $from;
// setting to itself, then not used?
$replytoEmail = $replytoEmail;
return $from;
// this will never return?
return $replytoEmail;
}
Why not work my function in wordpress?
My code
add_post_meta( $ids, 'price', $price, true );
$price_add = get_post_meta($id, 'price', true);
function myprice(){
if ($price_add != ' '){
echo $price_add." Euro";
}
else {
echo "None";
}
}
I try use if (isset($price_add)) but not work.
I want to show price introduced in or show text "None".
You are attempting to use a variable which is not "in scope". You might want to read the PHP manual page on variable scope.
A function is a reusable piece of code, with input and output, and in PHP variables are "scoped" (visible) to the function they are declared in. (The main exception is global variables, which are usually frowned on as they make code hard to read, reuse, and test; static variables and object members work a bit differently.)
In your case, you want a function which takes as input a price, and echoes that price if it is not an empty string (or, as you've written it, a single space); you might define that like this:
function myprice($price_to_display) {
if ($price_to_display != ' '){
echo $price_to_display." Euro";
}
else {
echo "None";
}
}
You then call that somewhere else, passing in the value you want to display, like this:
$price_add = get_post_meta($id, 'price', true);
myprice($price_add);
Note that I've named the variable in the function something different for clarity; you could call it $price_add, but that wouldn't make it connected to the other variable called $price_add in any special way.
[Edited to add...] In fact, you don't need to have a variable at all when you are calling the function - what you are providing is a value for the input parameter. So you could also write it like this:
myprice( get_post_meta($id, 'price', true) );