problem with else if statement not working - php

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

Related

create a function and modify a post on the wordpress site based on the post id

I'd want to edit the content of one of my posts using this way, but it's not working.
Does this filter affect the php output or the raw php file?
add_filter( 'the_content', 'multiple_string_replacements');
function multiple_string_replacements ( $contentt ) {
if ( is_single('15467') && in_the_loop() && is_main_query() ) {
$condition = true;
if($condition){
$urlsdothejob = "link.com";
$text = array(
"$variable1" => "$urlsdothejob",
"$variable2" => "$urlsdothejob",
);
$contentt = str_ireplace(array_keys( $text ), $text, $contentt);
};
}
return $contentt;
}
If you know the conditions that you're looking for, you should be able to write an IF statement to match.
if ($constantvalue == "anothervalue") {
// make local changes
}
Can you give an example of what you're trying to do? It's hard to understand the request with such little information.
Try like this hope its working for you.
while(have_posts()):
$ID = get_the_ID();
$data1 = get_post_meta($ID,'meta_key',true);
$data2 = get_post_meta($ID,'meta_key',true);
if($data1 == $data2) {
update_post_meta($ID,'meta_key','meta_value');
}
endwhile;

Is it possible to run server side validation for Ninja Forms using file_get_contents()?

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 ) {

php same parameters different value

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

PHP form validate using foreach and store value if and only there is no error

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.

php if $_GET equals a certain array

I'm trying to use the break concept, but I am also am using some built in PHP functions to only allow certain values into the get function.
$allowedKeys = array(
'route'
);
$options = array(
'chapter_1' => 'chapter_1',
'chapter_2' => 'chapter_2',
'chapter_3' => 'chapter_3'
);
$_GET = array_intersect_key($_GET, array_flip($allowedKeys));
if($_GET[$allowedKeys[0]] && array_key_exists($_GET[$allowedKeys[0]], $options)) {
if($_GET[$allowedKeys[0]] == $options[0]) {
/* This is where I'm trying to see if route=chapter_1 then do something.
The logic I'm trying to write is if the route is chapter_1 then print
out the content from chapter 1 How can determine this? */
echo "Hello";
}
}
Why isn't this code echoing "hello"?
Why make it more complex than it needs to be?
//check you have a route
$route = isset( $_GET['route'] ) ? $_GET['route'] : '';
switch( $route ) {
case 'chapter_1':
//do chapter one stuff
echo 'Chapter 1';
break;
case 'chapter_2':
//do chapter two stuff
echo 'Chapter 2';
break;
default:
echo 'Intro';
}
I'll answer your question directly for you. 'Hello' isn't showing because it is inside an if statement that isn't being triggered because either "if($_GET[$allowedKeys[0]] && array_key_exists($_GET[$allowedKeys[0]], $options))" or "if($_GET[$allowedKeys[0]] == $options[0])" is returning false.

Categories