unset item from array and update wp option - php

I have a series of checkboxes, each of which triggers an ajax action in WordPress. It sends an id number and the state of the checkbox to my php function. The function checks two wp_options. If the checkbox is checked, it looks for the id number in one option's array and if it's not in the array, it adds it. It also looks for the id number in the second option's array and if it is in the array, it's supposed to unset it. If the checkbox is unchecked, it does the opposite.
It's successfully adding items to the first option's array, but I can't get it to unset the item from the second option's array. It returns "error" every time. Here's the function, minus the nonce info:
function my_required_fields(){
$field = $_POST['field'];
$checked = $_POST['checked'];
$required_fields = get_option('ghsc_required_fields') ? unserialize(get_option('ghsc_required_fields')) : array();
$optional_fields = get_option('ghsc_optional_fields') ? unserialize(get_option('ghsc_optional_fields')) : array();
if($checked === 'yes'):
if(!in_array($field, $required_fields)): $required_fields[] = $field; endif;
if(in_array($field, $optional_fields)): unset($optional_fields[$field]); endif;
elseif($checked === 'no'):
if(!in_array($field, $optional_fields)): $optional_fields[] = $field; endif;
if(in_array($field, $required_fields)): unset($required_fields[$field]); $required_fields = array_values($required_fields); endif;
endif;
$update_required = update_option('ghsc_required_fields', serialize($required_fields));
$update_optional = update_option('ghsc_optional_fields', serialize($optional_fields));
$response = ($update_required && $update_optional) ? 'success' : 'error';
$response = json_encode($response); header( "Content-Type: application/json" ); echo $response; exit;
}
Any idea what I'm doing wrong?

I worked it out. Needed to use array_keys (or an alternative) to unset the key, rather than the value, and also needed to check to see if the value of the option had changed, because if it hadn't it would return false. See below:
function my_required_fields(){
$field = $_POST['field'];
$checked = $_POST['checked'];
$required_fields = get_option('ghsc_required_fields') ? unserialize(get_option('ghsc_required_fields')) : array();
$optional_fields = get_option('ghsc_optional_fields') ? unserialize(get_option('ghsc_optional_fields')) : array();
if($checked === 'yes'):
if(!in_array($field, $required_fields)): $required_fields[] = $field; endif;
if(in_array($field, $optional_fields)): foreach(array_keys($optional_fields, $field, true) as $key) unset($optional_fields[$key]); endif;
elseif($checked === 'no'):
if(!in_array($field, $optional_fields)): $optional_fields[] = $field; endif;
if(in_array($field, $required_fields)): foreach(array_keys($required_fields, $field, true) as $key) unset($required_fields[$key]); endif;
endif;
$update_required = (get_option('ghsc_required_fields') === serialize($required_fields) ? 1 : update_option('ghsc_required_fields', serialize($required_fields)));
$update_optional = (get_option('ghsc_optional_fields') === serialize($optional_fields) ? 1 : update_option('ghsc_optional_fields', serialize($optional_fields)));
$response = ($update_required && $update_optional) ? 'success' : 'error';
$response = json_encode($response); header( "Content-Type: application/json" ); echo $response; exit;
}

Related

Can you display an empty value with an array if the value is missing?

I have this piece of code.
What it does is it shows the supplier name via email.
The problem is that if the supplier name is empty as some dont need it, i get an error which redirects me to this piece of code.
Is there a way for me to say that if the suppliername is empty, to show as none?? or as a blank space?
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
echo $array1supplier['supplier'];
?>
To check if the array has a key you can use the isset function like so:
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
echo (isset($array1supplier['supplier'])) ? $array1supplier['supplier'] : '';
Use empty() function to check if empty or not.
Code:
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
if(empty($array1supplier['supplier'])) {
echo "Supplier is empty!";
} else {
echo $array1supplier['supplier'];
}
?>
or
You Can also use isset() function to check if it is set or not.
Code:
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
if(isset($array1supplier['supplier'])) {
echo $array1supplier['supplier'];
} else {
echo "Supplier is empty!";
}
?>
or
You can just use if($array1supplier['supplier'] == "")
Code:
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
if($array1supplier['supplier'] == "") {
echo "Supplier is empty!";
} else {
echo $array1supplier['supplier'];
}
?>
All of them are same, you can choose anything you want
It seems like you are expecting an array to be returned from get_post_meta()
According to WP Code Reference:
get_post_meta ( int $post_id, string $key = '', bool $single = false )
Retrieve post meta field for a post.
Return: (mixed) Will be an array if $single is false. Will be value of
meta data field if $single is true.
So the last parameter should be false.
Use isset() to determine if a variable is set and is not NULL
Try this:
$array1supplier = get_post_meta($productId, 'fancyincarray', false);
echo (isset($array1supplier['supplier'])) ? $array1supplier['supplier'] : "Empty";
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
echo (!empty($array1supplier['supplier'])
? $array1supplier['supplier']
: '';
?>

If parent slug equals

I'm trying to write an if statement where, if a child page's has a slug equal to a specific value, a different statement is echoed. Regardless of the slug value, the function always returns the else value rather than any other.
<?php
global $post;
$post_data = get_post($post->post_parent->post_name);
if ($post_data == 'slug-one'){
$ticket = 'Cats';
} elseif ($post_data == 'slug-two') {
$ticket = 'Dogs';
} else {
$ticket = 'Birds';
}
echo $ticket;
?>
Any ideas as to how I can better write the statement, or what the error occurring is?
As it turns out, I shouldn't have called $post_data = get_post($post->post_parent->post_name). My fixed code is below. Thanks for the advice everyone.
<?php
global $post;
$post_data = get_post($post->post_parent);
if ($post_data->post_name == 'in-the-city'){
$ticket = 'Cats';
} elseif ($post_data->post_name == 'on-the-beach') {
$ticket = 'Dogs';
} else {
$ticket = 'Birds';
}
echo $ticket;
?>

PHP write a conditional statement based on whether an argument is in a database or not

I am developing a wordpress plugin. There is a variable that I send to the database once a payment has been made, that is ispayment and it is set to 1. If the payment has not been made, then the variable is not sent to the database...so there is an instance where, for a particular post ID, the variable "ispayment" does not exist.
I'm now trying to write a conditional statement based on whether this variable is present or not.
What I'm trying to say is, if wedding_form_final_submit = 1 AND there is no ispayment variable - $status = foo. Else, if wedding_form_final_submit = 1 AND ispayment = 1, $status = bar.
Here is what I have so far:
if(get_post_meta($post_id,'wedding_form_final_submit', 1) && get_post_meta($post_id, 'ispayment',false)) {
$status = 'Form Complete';
} elseif(get_post_meta($post_id,'wedding_form_final_submit', 1) && get_post_meta($post_id, 'ispayment',true)) {
$status = 'Deposit Paid';
} else {
$status = '';
}
Currently, this just returns "Form Complete" but it's for an entry that should return Deposit Paid, the entry that should say Form Complete is just blank.
I believe my issue is that for my first statement, the variable ispayment doesn't exist. How do I ammend this though?
This code below will probably do, if the post meta you're retrieving doesn't exist, your variable just return empty
// get post meta value 'ispayment'
$paid = get_post_meta( $post_id, 'ispayment', true );
//Check where post meta exists and value is 1
if ( isset($paid) && $paid === '1' ) {
$status = 'Form Complete';
//If post meta doesn't exist or value is not 1.
} else {
$status = 'Deposit Paid';
}
//or shorter
$paid = get_post_meta( $post_id, 'ispayment', true );
$status = ( isset($paid) && $paid === '1' ) ? 'Form Complete' : 'Deposit Paid';
just add your other code in there

Validate with arrays

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;
}
}
}

$_POST checking empty

I need a function which can check my $_POST array, for example see this code, there is nothing common in the $_POST array. But i want to check if the array is returning null value from the user.
<?php
switch ($_GET['action']) {
case "one":
$a=$_POST['a'];
echo "your value is". $a;
break;
case "two":
$b=$_POST['b'];
$c=$_POST['c'];
echo "your value is". $b."--".$c;
break;
case "three":
$x=$_POST['x'];
$y=$_POST['y'];
$z=$_POST['z'];
echo "your value is". $x."--".$y."--".$z;
break;
}
?>
Check like this:
$x = (isset($_POST['x']) && $_POST['x'] != "") ? $_POST['x'] : "" ;
echo "your value is". $x.";
As per your comment my updates:
function check_empty($item, $key)
{
$item[$key] = (isset($item) && $item != "") ? $item : "" ;
}
array_walk($_POST, 'check_empty');
You can check if the $_POST array is empty using
empty($_POST)
And if you want to check for individual value is null,
empty($_POST['x'])
Something like:
$x = !empty($_POST['x']) ? $_POST['x'] : '';
You are looking for isset()
$a = null;
if ( isset($_POST['a']) ) {
$a = $_POST['a'];
}

Categories