Assistance Needed with Custom WooCommerce Plugin for Product Tags

[ad_1]

Hello WordPress Community,

I am currently working on a custom WooCommerce plugin and have encountered a challenge that I’m hoping to get some assistance with.

Plugin Description:
The plugin is designed to enhance the functionality of product tags in WooCommerce. It allows adding custom settings to product tag edit pages, enabling automatic display of products in a tag based on selected product attributes and variations. Essentially, the plugin should filter products on a tag page without manually adding products to the tag.

Problem:
I have successfully added custom fields in the product tag edit section for selecting attributes and their variations. However, I’m facing an issue with the pre_get_posts action hook. The goal is to modify the query on the tag page to display products that match the selected attributes and variations. Despite several debugging attempts, the products are not being filtered as expected on the tag page.

Here’s a brief overview of what I’ve implemented:

Custom fields in the product tag edit page for selecting attributes and variations.
Saving the selected values as term meta.
A function hooked to pre_get_posts to modify the product query based on the selected attributes and variations.
Specific Issue:
The main challenge is that the pre_get_posts function does not seem to be affecting the product query as intended. I’ve added error logging for debugging, but it’s not providing the needed insights.

I would greatly appreciate any guidance or suggestions on how to resolve this issue. If more specific details or snippets of code are needed, I am happy to provide them.

<?php

// Add custom fields to the product tag edit page
function edit_product_tag_fields($term) {
    // Get a list of all attributes
    $attributes = wc_get_attribute_taxonomies();

    // Retrieve saved values for the tag
    $saved_values = get_term_meta($term->term_id, 'selected_attributes', true);
    $saved_values = $saved_values ? $saved_values : array();

    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="selected_attributes"><?php _e('Select Attributes and Variations', 'text_domain'); ?></label></th>
        <td>
            <?php foreach ($attributes as $attribute) : 
                // Get variations for the attribute
                $terms = get_terms('pa_' . $attribute->attribute_name, array('hide_empty' => false));
            ?>
                <strong><?php echo esc_html($attribute->attribute_label); ?>:</strong><br>
                <?php foreach ($terms as $term) : ?>
                    <input type="checkbox" name="selected_attributes[]" id="term_<?php echo esc_attr($term->term_id); ?>" value="<?php echo esc_attr($term->slug); ?>" <?php checked(in_array($term->slug, $saved_values)); ?>>
                    <label for="term_<?php echo esc_attr($term->term_id); ?>"><?php echo esc_html($term->name); ?></label><br>
                <?php endforeach; ?>
                <br>
            <?php endforeach; ?>
        </td>
    </tr>
    <?php
}
add_action('product_tag_edit_form_fields', 'edit_product_tag_fields', 10, 2);

// Save the selected attributes and variations when updating the tag
function save_product_tag_fields($term_id) {
    error_log(print_r($_POST['selected_attributes'], true));
    if (isset($_POST['selected_attributes'])) {
        update_term_meta($term_id, 'selected_attributes', $_POST['selected_attributes']);
    } else {
        delete_term_meta($term_id, 'selected_attributes');
    }
}
add_action('edited_product_tag', 'save_product_tag_fields', 10, 2);

// Modify the database query to display products based on selected attributes and their variations
function filter_products_by_selected_attributes($query) {
    error_log('Function called at the start');
    error_log('Function filter_products_by_selected_attributes called');
    
    if (!is_admin() && $query->is_main_query() && is_tax('product_tag')) {
        error_log('Inside conditional block');
        
        $tag = get_queried_object();
        $selected_variations_serialized = get_term_meta($tag->term_id, 'selected_attributes', true);
        $selected_variations = maybe_unserialize($selected_variations_serialized);
          
        error_log('Selected variations: ' . print_r($selected_variations, true));
          
        if (!empty($selected_variations) && is_array($selected_variations)) {
            $tax_query = array('relation' => 'AND');
            $attribute_taxonomies = wc_get_attribute_taxonomies();

            foreach ($selected_variations as $variation_slug) {
                foreach ($attribute_taxonomies as $attribute) {
                    $taxonomy = 'pa_' . $attribute->attribute_name;
                    $terms = get_terms(array(
                        'taxonomy' => $taxonomy,
                        'slug' => $variation_slug,
                        'hide_empty' => false,
                    ));

                    if (!empty($terms)) {
                        $tax_query[] = array(
                            'taxonomy' => $taxonomy,
                            'field'    => 'slug',
                            'terms'    => array($variation_slug),
                        );
                        break; // Exit the loop as we found the matching term
                    }
                }
            }

            if (count($tax_query) > 1) {
                error_log(print_r($tax_query, true));
                $query->set('tax_query', $tax_query);
            }
        }
    }
}
add_action('pre_get_posts', 'filter_products_by_selected_attributes');

Thank you in advance for your time and assistance.

Best regards,

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer