exception handling for undefined index error? - php

The script below is called when saving my app's options page. All options are stored in an array in $options.
I'm getting a debug error "undefined index, id" on the line with the comment below. Any ideas how I can fix the script?
foreach ($options as $value)
{
if( isset( $value['id'] ) && isset( $_REQUEST[$value['id']] ) )
{
update_option( $value['id'], stripslashes($_REQUEST[$value['id']]) );
}
else
{
update_option( $value['id'], ""); //Error Here
}
}

Your if{} segment precludes the code in your else{} segment from working.
In other words:
In your if block, you ask: "Does $value['id'] exist?"
If it does not, your code executes your else block, which then attempts to reference the non-existent variable.
You'll need to set the array key before you can update it.
Your update_option function should simply check to see if the variable exists, and set it instead of updating it, if it does not.

Related

How to fix "Undefined array key"

I have problem every time I try to actualize Elementor from 3.9.2 to 3.10 - I see an error
"Warning: Undefined array key "file" in (...)/wp-includes/media.php on line 1680".
It appears at the bottom of my homepage. After backup everything's working well.
The code is:
// Bail early if an image has been inserted and later edited.
if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
return $image;
}
I'm a noob un php so I need some help to fix it. Don't know what to do.
It may be helpful to know that I have set short film as a background in first section on homepage.
I tried to find this array definition but I have no idea wehere it is.
I used # in code but I know it's not recommended so I want to find better solution
// Bail early if an image has been inserted and later edited.
if ( preg_match( '/-e[0-9]{13}/', $#image_meta['file'], $img_edit_hash ) &&
strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
return $image;
}
Found this:
https://wordpress.org/support/topic/bug-with-php-8-0-version/
So one way is to decrease PHP version to 7.4.

How to check if $meta_key in array has a value before running an if-statement

I am working on a some code that will post information from custom field to the database.
The following code checks to see if the $meta_key is present:
// Apply filters to keys
$this->keys = apply_filters('sc_meta_keys', $this->keys);
// See if the current meta_key is in the array keys
if($this->in_array_recursive($meta_key, $this->keys)) {
if($action == "add") {
//information from array gets added to DB
}
}else{
//Do something else
}
I am however unsure how to check if there is a value in the meta_key, as I don't want the if-statement to run if there is no value present.
The array will always have keys however not every post will necessarily have the custom fields filled.
Probably you should do this. This would check if $metakey exists .
// See if the current meta_key is in the array keys
if (isset( $meta_key )) && (is_array($meta_key) && ($this->in_array_recursive($meta_key, $this->keys))) {
You should always check if a variable is set and utlize short circuit operators to reduce the processing time of the conditionals. As You haven't included the logic for where you are setting $meta_key I'll check if it's set or not to be sure.
$this->keys = apply_filters('sc_meta_keys', $this->keys);
// See if the current meta_key is in the array keys
if( isset( $meta_key ) && ! empty( $this->keys ) && $this->in_array_recursive( $meta_key, $this->keys ) ) {
if($action == "add") {
//information from array gets added to DB
}
}
else {
//Do something else
}

How to loop through CSV string data of an ACF field and print each value only once?

I know how to print a single value with echo in PHP, but I am stuck when it comes to printing each value in comma separated array one value at a time.
This is what I have:
<?php echo wp_kses_post(get_field('field')); ?>
where field is equal to a predefined single value like stackof which I can modify to a CSV string like stackof, stackog, stackoh, stackoi,....
This is what I want (from OP's comments):
On admin panel, there is a field that I can enter any value. Lets call this value as code. This code is directly printed on the frontend when a button is clicked.
I want to print unique and predefined code whenever the button is clicked.
To do so, I can enter comma separated codes in the field on admin panel such as CSV string like this stackof, stackog, stackoh, stackoi,.... But it will print all the codes on the screen.
I need to print each unique codes on the screen one by one when button is clicked. Also, once a code is printed, it shouldn't be printed again.
Note: This loop is not tied to user sessions. So every time any user clicks the button a new code from the CSV field should be printed and older ones should be marked used or discarded.
This function should work for you to get the latest code which was never printed. How you call this function is entirely up to you. You can either hook into your ajax code or add new template altogether.
<?php
function get_next_val_from_field( $field_name, $post_id = false ){
// Let's get the field data as string.
$field_data = get_field( $field_name, $post_id );
// Did we recieved any data?
if( ! empty( $field_data) ) {
// Convert CSV string to an array.
$field_data = explode( ',', $field_data );
// Remove any empty values and trim extra spaces from around the values.
$field_data = array_map( 'trim', array_filter( $field_data ) );
// Rechecking if array is not empty.
if( is_array( $field_data ) && ! empty( $field_data) ) {
// Prefix to know next value inside the string.
$next_value_prefix = 'mm1707_next--';
$next_value_found = false;
// Loop through each value to find next value, if any.
foreach ($field_data as $key => $value) {
if ( 0 === strpos( $value, $next_value_prefix ) ) {
$next_value = str_replace( $next_value_prefix, '', $value);
$field_data[ $key ] = $next_value;
$next_value_found = true;
} elseif ( $next_value_found ) {
// Now that we have found next value let's mark following
// array item as next value and break the loop.
$field_data[ $key ] = $next_value_prefix . $value;
// No need for further loop now.
break;
}
}
// If there wasn't any current value then print first value & mark next one.
if( empty( $next_value ) ){
$next_value = $field_data[0];
$field_data[1] = $next_value_prefix . $field_data[0];
}
// Let's update the field inside DB to save currently marked data.
update_field( $field_name, implode(',', $field_data ), $post_id );
return $next_value;
}
}
}
Essentially,
We are converting CSV string into an array.
Then we find the value from the array with mm1707_next-- prefix,
If found then return it, remove the prefix from that value and mark next array value with that prefix.
If there is no value with that prefix then let's start from first value.

How to check a dynamic attribute of one object in PHP ?

In php, I must check if the first attribute of a PHP object is null. the problem is I do not know the key because the object is set dynamicaly and can be an Object A or Object B etc...
if( empty( $this->editable_item->item ) || $this->editable_item->item->? === null ){ <-- ? the key can be various things
//Do something like log an error
}
How can check the first attribute without knowing its key ?
To do this, you need to use the function get_object_vars() and use reset like this :
$a_vars = get_object_vars( $this->editable_item->item );
reset( $a_vars );
$first_key = key( $a_vars );
if( empty( $this->editable_item->item ) || empty( $a_vars[$first_key] ) ){
//Do something like log an error
}

Read boolean session variable in WordPress after checking in functions

I need to check if there is a session on every WordPress page. I used add_action Init with the following code:
function check_session() {
$se;
if ( session_status() == PHP_SESSION_NONE ) {
$se = false;
} elseif ( session_status() == PHP_SESSION_ACTIVE ) {
session_start();
if ( isset( $_SESSION['mysession'] ) ) {
$se = true;
}
}
}
add_action( 'init', 'check_session');
Now, I want to show prices or others depending on whether or not that session exists. I tried to set a boolean variable after checking the session and programming the code based on that variable, but I can not read it in the file of my template, neither in the index.php or head.php, I guess it will not be visible. What is the way to read the boolean variable in the files of the wordpress theme, or is there a better way to do this? I have read about global variables but everyone advises against using them.
To see if anyone can take my doubts away, I greet you!

Categories