1

Hi can anyone please help.

I'm no computer buff and need a step-by-step guide if possible.

In getting this error on my product pages:

Warning: Undefined variable $post_id in /customers/5/f/d/haveitpersonalised.com/httpd.www/wp-content/plugins/extra-product-addons-for-woocommerce/App/Helpers/FieldsFromCategoryPosts.php on line 47

this is the PHP-file:

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class FieldsFromCategoryPosts{
    
    public static function getFieldsFromCategoryPosts($category_id, &$post_found_ids, $exclude_id = null){

        $post_type = EPAFW_POST_TYPE;
        $fields_json = [];
    
        $args = array(
            'post_type' => $post_type,
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'id',
                    'terms' => $category_id,
                ),
            ),
        );
    
        $posts_with_category = get_posts($args);
    
        if (!empty($posts_with_category)) {
            foreach ($posts_with_category as $post) {
                $post_id = $post->ID;
                
                // Check if the post ID has already been processed.
                if (!in_array($post_id, $post_found_ids)) {
                    if (get_post_status($post_id) == 'publish' && ($exclude_id === null || $post_id !== $exclude_id)) {
                        $fields_json[] = json_decode(get_post_meta($post_id, EPAFW_FORM_META_KEY, true));
                    }
                    // Append the post ID to the array to mark it as processed.
                    $post_found_ids[] = $post_id;
                }
            }
        }  
        // echo "<pre>";
        // var_dump($post_id);
        // echo "</pre>";
        $fields = array_merge(...$fields_json);
        return array(
            'post_id' => $post_id,
            'fields' => $fields,

Any help much appreciated Thank you

2 Answers 2

1

Try this instead:

$posts_with_category = new WP_Query( $args );

if( $posts_with_category->have_posts() ) {

Instead of just checking if $posts_with_category is non-empty it checks if it's an array of WP_Post objects.

We don't have line numbers to see where the error is being thrown. Is line 47 your return statement?

2
  • Hi Chris Tired the substitute code and the whole page messed up totally .. Any other ideas more than welcome
    – Andy
    Commented Aug 22 at 14:25
  • When you say "the whole page messed up totally", what error is it throwing?
    – Chris Cox
    Commented Aug 22 at 14:43
0

The error Warning: Undefined variable $post_id occurs because the $post_id variable is being used in the return statement even though it may not have been defined or initialized in the loop. This can happen if $posts_with_category is empty, causing the loop to never execute and thus leaving $post_id undefined.

To fix this, you need to ensure that $post_id is defined before you attempt to use it, even if the loop doesn't run.

Step-by-Step Fix

Initialize the $post_id variable before the loop. This ensures that $post_id always has a value, even if the loop doesn't execute.

Return a sensible value if there are no posts found. This could be null or some other indicator that no posts were found.

Here’s how you can modify your code:

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class FieldsFromCategoryPosts {

    public static function getFieldsFromCategoryPosts($category_id, &$post_found_ids, $exclude_id = null) {

        $post_type = EPAFW_POST_TYPE;
        $fields_json = [];
        $post_id = null; // Initialize $post_id with null

        $args = array(
            'post_type' => $post_type,
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'id',
                    'terms' => $category_id,
                ),
            ),
        );

        $posts_with_category = get_posts($args);

        if (!empty($posts_with_category)) {
            foreach ($posts_with_category as $post) {
                $post_id = $post->ID;

                // Check if the post ID has already been processed.
                if (!in_array($post_id, $post_found_ids)) {
                    if (get_post_status($post_id) == 'publish' && ($exclude_id === null || $post_id !== $exclude_id)) {
                        $fields_json[] = json_decode(get_post_meta($post_id, EPAFW_FORM_META_KEY, true));
                    }
                    // Append the post ID to the array to mark it as processed.
                    $post_found_ids[] = $post_id;
                }
            }
        }  

        $fields = !empty($fields_json) ? array_merge(...$fields_json) : []; // Handle empty $fields_json

        return array(
            'post_id' => $post_id,  // This will be null if no post was found
            'fields' => $fields,
        );
    }
}

Explanation

Initialization of $post_id:

Before the loop, $post_id is initialized to null. This avoids the warning and makes it clear that if no posts are found, $post_id will remain null. Handling of $fields_json:

The array_merge(...$fields_json) is only executed if $fields_json is not empty. If it's empty, $fields is set to an empty array.

Return Values:

If no posts match the criteria, the function will return null for post_id and an empty array for fields. This is a sensible default that you can handle elsewhere in your code.

Result

This should eliminate the Undefined variable $post_id warning and provide a more robust and predictable function. If you need to handle the case where no posts are found differently, you can check for null in the calling code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.