I have a Wordpress plugin that when searching multiple types of cars ads multiple values of the same parameter in the url.
/home/?condition=filter1&condition=filter2&s=
Now I created multiple user roles for different cars and want to add a filter to the site.
This code works with 1 value
function wprdcv_param_redirect() {
$user = wp_get_current_user();
$url_parts = parse_url("http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
parse_str($url_parts['query'], $params);
if( ! empty( $user ) && count( array_intersect( [ "userrole1" ], (array) $user->roles ) ) ) {
//Prevent infinite loop
if ($_GET["condition"] == "filter1") return;
$params["condition"] = "filter1";
$params["s"] = "";
}
else {
//Prevent infinite loop
if ($_GET["condition"] == "") return;
$params["condition"] = "";
$params["s"] = "";
}
foreach (array_keys($_GET) as $n) {
$params[$n] = $_GET[$n];
}
// Note that this will url_encode all values
$url_parts['query'] = http_build_query($params);
wp_redirect(http_build_url($url_parts));
exit;
}
add_action('template_redirect', 'wprdcv_param_redirect');
When I add the following it offcourse overwrites the value and only shows the last one:
if ($_GET["condition"] == "filter1") return;
$params["condition"] = "filter1";
$params["condition"] = "filter2";
$params["s"] = "";
how can I edit this so it shows me 2 same parameters with different values?
EDIT:
I have adding following and it works like a charm!
$params["condition"][] = "Filter1";
$params["condition"][] = "Filter2";
Thx fellas! #CBroe & #Vincent Decaux
/home/?condition%5B0%5D=Filter1&condition%5B1%5D=Filter2&s= proves to be perfectly working
Related
I've been banging my head all day on this last piece of my project. I'm using Ninja Forms and looking to validate a string before submitting the form. I have broken this into pieces and tested using simple string checks and it worked but when I try to use the file_get_contents() function it's just submitting without running the check. The file realtor_info.txt contains the following: mikeoberdick#gmail.com - BP61AM. The page is found here: https://www.rhwarranty.com/realtor-quote/
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data');
function my_ninja_forms_submit_data( $form_data ) {
$form_id = $form_data[ 'form_id' ];
if ( $form_id = 4 ) {
$email_field_id = 41;
$coupon_field_id = 49;
$email = $form_data['fields'][$email_field_id]['value'];
$coupon = $form_data['fields'][$coupon_field_id]['value'];
$string = $email . ' - ' . $coupon;
$file = "https://rhwarranty.com/wp-content/themes/regal-home-warranty/stripe/realtor_info.txt";
//check the file to see if the string exists
if( strpos(file_get_contents($file),$string) !== false) {
return $form_data;
} else {
$form_data['errors']['fields'][$coupon_field_id] = 'Something is not quite right here!';
}
}
}
Any thoughts on what is going wrong?
Why do you assign the value of the form in the if statement ?
Or if ( $form_id = 4 ) {
this should be
if ( $form_id == 4 ) {
I'm trying to pass variables from a foreach function that fetch a mysql query to an array, to another function.
I declare the array before the foreach to make it global but no data are passed to the function.
here is my code. If you have any idea of what i'm doing, thanks by advance for your help.
Of course if I replace the called function by what's inside it, everything works like a charm.
but as I'll have to use it several times I would prefer to set my variables in a function.
function fillStuInfos() {
global $studFName, $studLName,c$dateStart, $dateEnd;
$studFName = $EventsGt['fName'];
$studLName = $EventsGt['lName'];
$dateStart = $EventsGt['startDate'];
$dateEnd = $EventsGt['endDate'];
}
$email = $_POST['email'];
$EventsGt = array();
$getEventsQry = 'SELECT * FROM Companies WHERE Email_Company = "'.$email.'" ORDER BY startDate';
foreach ($bddPDO->query($getEventsQry) as $EventsGt) {
$intCur = date_diff(date_create($today), date_create($EventsGt['endDate']));
$intFut = date_diff(date_create($today), date_create($EventsGt['startDate']));
echo intval($intCur->format('%r%a'));
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos();
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos();
} else {
echo 'No Datas!';
exit();
}
}
echo $studLName;
Forget that exists global and pass params to function.
function fillStuInfos($data) {
$studFName = $data['fName'];
$studLName = $data['lName'];
$dateStart = $data['startDate'];
$dateEnd = $data['endDate'];
}
...
foreach (...) {
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos($EventsGt);
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos($EventsGt);
} else {
echo 'No Datas!';
exit();
}
}
Your variable you want to be global is $EventsGt, not $studFName, $studLName, $dateStart, $dateEnd
With that said, I would recommend passing the event array as a parameter or passing the individual values as parameters instead.
I have created a custom WordPress filter. I am importing api data to a form. My first IF statement works (when district not empty). But I can't get the else if working to populate the 2nd field. The 2nd result in the JSON has no value for district. What I am trying to do is separate the results to display House rep in one field and Senators in another. (There are actually two Senate results but I don't now how to separate the results). Each result needs to be in different form fields.
add_filter('frm_pre_create_entry', 'import_fields');
function import_fields($values){
if ( $values['form_id'] == 12 ) {
$zipcode = $values['item_meta'][71];
$api_request = 'http://whoismyrepresentative.com/getall_mems.php?zip='.$zipcode.'&output=json';
$api_response = wp_remote_get( $api_request );
$api_data = json_decode( wp_remote_retrieve_body( $api_response ), true );
foreach ( $api_data["results"] as $member ) {
if ( $member["district"] != '' ) {
$values['item_meta'][72] = $member['name'];
$values['item_meta'][73] = $member['phone'];
$values['item_meta'][74] = $member['office'];
} else if ( $member["district"] == '' ) {
$values['item_meta'][75] = $member['name'];
$values['item_meta'][76] = $member['phone'];
$values['item_meta'][77] = $member['office'];
}
break;
}
}
return $values;
}
I am new here, please go easy on me.
just like #billyonecan said, that break looks weird.
PS: You don't even need to specify the 'else if' condition... simply replace the 'else if' by 'else'
...
} else if ( $member["district"] == '' ) {
...
becomes
...
} else {
...
In your case it won't make any difference, it's just good practices
I am having array of for fields and saving data to the database without issue if I submit without validation.
The trouble I am having is to check for errors existence in foreach iteration before saving any single field data using update_setting( $optionname, $optionvalue );
Current code is saving data for all fields but the error one. So is there any way to first validate all fields and only store to database if there is no single error. Otherwise shoot error message on the page.
$errors = [];
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
// check the field if not set
if ( get_post_field( 'test' ) == '' ) {
$errors['test'] = 'Test field is required';
}
/**
* all loop items only should be add/update if there is not single error
* If any single error occure than it shold not save any single field data
*/
// add/update settings
elseif ( empty( $errors ) ) {
update_setting( $optionname, $optionvalue );
}
}
trivial but may work :)
$errors = [];
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
// check the field if not set
if ( get_post_field( 'test' ) == '' ) {
$errors['test'] = 'Test field is required';
}
/**
* loop all variables
*/
}
if ( count( $errors ) == 0) {
foreach ( $optionnames as $optionname ) {
$optionvalue = get_post_field( $optionname );
update_setting( $optionname, $optionvalue );
}
} else {
//routine or whatever you want to fire errors on the page
}
Rather than hitting the database with an UPDATE query every iteration, why not just run one query? Regardless, you can achieve your goal if you break your code up into two foreach loops, as so:
// first loop validates each option
$errors = [];
foreach($optionNames as $optionName){
$optionValue = get_post_field($optionName);
if( strlen(trim($optionValue)) == 0 ){
$errors[] = sprintf("%s field is required!", $optionName);
// you could break here if you do not want to accumulate error messages
}
}
// if any errors were found, halt execution and output error messages
if( count($errors) > 0){
$errorMessages = implode(",", $errors);
die("Cannot save due to the following errors: " . $errorMessages);
}
// this will only execute if no errors were found
foreach($optionNames as $optionName){
$optionValue = get_post_field($optionName);
update_setting( $optionName, $optionValue );
}
This is not how I would go about doing this, but I chose to answer your question using the code you provided rather than providing something entirely different.
Try to avoid using "else" in situations where returning early (or in my example, halting execution) is an option. It helps clean up your code by providing a clear path to the desired outcome.
I'm trying to find a smarter way to validate my inputs with PHP. If the array finds an empty field, it has to add a new element to the array and display an error message.
So far, I haven't succeeded.
The code behind
$felter = array();
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
else {
$sql = "UPDATE produkt SET produkt_navn = '$produktnavn', fk_kategori_id = '$kategori' WHERE produkt_id=$id";
mysqli_query($db, $sql);
echo "Produktet blev opdateret";
}
Input form
<input type="text" class="form-control" name="produktnavn" value="<?php echo $produktnavn; ?>">
The code starts with $felter = array(); which initializes an empty array.
Then, without changing the array itself, you're checking for non-emptiness of $felter
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
You're trying to iterate over an array that has not gotten any elements pushed into it. And the logic statement if( !empty ($felter)) will also not work as expected either.
As a test, before the check for !empty, put something in the array with $felter[] = 'Test word'; and then, underneath it... (if you're looking for a non-empty array, the logical checker could be if(count($felter)) { before iterating over the array with foreach ($felter as $felt) { if ($felt == '')
$felter = array();
$felter[] = 'Test word';
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( count( $felter ) ) {
foreach ($felter as $felt) {
if ($felt == '') {
$fejl = true;
}
}
}