John Davidson

php - Unsure why undefined variable notice trying to get product 'id' when adding ACF fields to custom column?

0 comments
Message:


I have added a custom column to WooCommerce Products page in Admin Dashboard, however when trying to populate column with adding 2 custom ACF fields setup for Post Type -> Products, I am receiving error notice on debug listed on every product in that custom column.



Notice: Undefined variable: product in
/./././wp-content/themes/bpa/functions.php on line 923


Notice: Trying to get product 'id' of non-object in
/./././wp-content/themes/bpa/functions.php on line 923



Could anyone please help explain what I'm doing wrong to get undefined variable?


Line 923 is :


        $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

Is it because I'm using an old approach for WC or something?


Full Function:


// Populate column
function woo_product_rmreference_column_data( $column ) {
global $post;

if ( $column == 'rm_reference' ) {

//
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

// Get ACF Fields
$reference = get_field( 'property_reference', $product_id );
$address = get_field( 'location', $product_id );

// Output
echo ($reference . $address) ? '<div>'.$reference.' - '.$address.'</div>' : '<div>Not found!</div>';
}
}
add_action( 'manage_product_posts_custom_column' , 'woo_product_rmreference_column_data', 10, 2 );


My Answer:
If you are receiving an "undefined variable" notice when trying to access a product in PHP, it means that the variable you are trying to access has not been defined or initialized before you are trying to use it.

To resolve this issue, you need to make sure that the variable containing the product information is defined and initialized before you try to access it. This can be done by checking if the variable is set using the `isset()` function or by initializing the variable with a default value before using it.

For example, if you are trying to access a product stored in a variable called `$product`, you can check if the variable is set before accessing it like this:

php
if(isset($product)) {
// Access the product information here
} else {
// Handle the case where the product variable is not set
}


Alternatively, you can initialize the variable with a default value before using it like this:

php
$product = null; // Initialize the variable with a default value

// Access the product information here


By ensuring that the variable containing the product information is defined and initialized before you try to access it, you can avoid the "undefined variable" notice in PHP.

Rate this post

3 of 5 based on 2089 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us