• Resolved komar132

    (@komar132)


    Hello,

    I’m trying to extend the WooCommerce “All Products” block by adding a category filter option. I want to allow users to select a product category from a dropdown in the block’s settings, and then filter the displayed products based on the selected category.

    I have added both the JavaScript and PHP code to handle this. The dropdown appears in the block’s settings, but the products in the block are not being filtered based on the selected category. I added some logging to track the process, but I can’t seem to get the filtering to work properly.

    Key issues:

    1. The category dropdown shows up in the block settings, but products do not filter based on the selected category.
    2. Logs indicate that the category is being selected, but the products are not updated accordingly.

    Here is the code I’ve used:

    javascript
    ( function( wp ) {
    var el = wp.element.createElement;
    var InspectorControls = wp.blockEditor.InspectorControls;
    var PanelBody = wp.components.PanelBody;
    var SelectControl = wp.components.SelectControl;
    var useSelect = wp.data.useSelect;

    wp.hooks.addFilter(
    'blocks.registerBlockType',
    'my-plugin/extend-all-products',
    function( settings, name ) {
    if ( name === 'woocommerce/all-products' ) {
    console.log('Registering new attributes for woocommerce/all-products block.');

    settings.attributes = Object.assign( settings.attributes, {
    selectedCategory: {
    type: 'string',
    default: ''
    }
    });

    var editFunction = settings.edit;

    settings.edit = function( props ) {
    console.log('Editing woocommerce/all-products block with props:', props);

    if (props.name === 'woocommerce/all-products') {
    var categories = useSelect( function( select ) {
    return select( 'core' ).getEntityRecords( 'taxonomy', 'product_cat', { per_page: -1 } ) || [];
    }, [] );

    console.log('Loaded categories:', categories);

    var categoryOptions = categories.map( function( cat ) {
    return { label: cat.name, value: cat.id };
    } );
    categoryOptions.unshift({ label: 'Select category', value: '' });

    return el(
    wp.element.Fragment,
    {},
    el( editFunction, props ),
    el(
    InspectorControls,
    {},
    el(
    PanelBody,
    { title: 'Category Settings' },
    el(
    SelectControl,
    {
    label: 'Select Category',
    value: props.attributes.selectedCategory || '',
    options: categoryOptions,
    onChange: function( newValue ) {
    console.log('Selected category:', newValue);
    props.setAttributes({ selectedCategory: newValue });
    }
    }
    )
    )
    )
    );
    }
    return el( editFunction, props );
    };

    settings.deprecated = [
    {
    attributes: settings.attributes,
    save: function( props ) {
    console.log('Saving block without changes in structure.');
    return null;
    }
    }
    ];
    }
    return settings;
    }
    );

    } )( window.wp );
    php

    <?php
    if (!defined('ABSPATH')) {
    exit;
    }

    class Utilities_Function_Kategorie {

    public function __construct() {
    add_action('enqueue_block_editor_assets', array($this, 'enqueue_category_filter_script'));
    add_filter('woocommerce_blocks_product_grid_query_args', array($this, 'filter_products_by_category'), 10, 2);
    }

    public function enqueue_category_filter_script() {
    wp_enqueue_script(
    'category-filter-block',
    plugins_url('category-filter.js', __FILE__),
    array('wp-blocks', 'wp-element', 'wp-components', 'wp-data', 'wp-editor'),
    filemtime(plugin_dir_path(__FILE__) . 'category-filter.js')
    );
    error_log('Category filter block script enqueued.');
    }

    public function filter_products_by_category($query_args, $attributes) {
    error_log('Filtering products by category with attributes: ' . print_r($attributes, true));

    if (isset($attributes['selectedCategory']) && !empty($attributes['selectedCategory'])) {
    error_log('Selected category ID: ' . $attributes['selectedCategory']);

    $query_args['tax_query'][] = array(
    'taxonomy' => 'product_cat',
    'field' => 'id',
    'terms' => array($attributes['selectedCategory']),
    'operator' => 'IN',
    );

    error_log('Updated query_args with tax_query: ' . print_r($query_args, true));
    } else {
    error_log('No category selected or selectedCategory attribute is empty.');
    }

    return $query_args;
    }
    }

    new Utilities_Function_Kategorie();
    • This topic was modified 1 month, 3 weeks ago by komar132.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi @komar132 ,

    Can you reform this,

    ( function( wp ) {
    var el = wp.element.createElement;
    var InspectorControls = wp.blockEditor.InspectorControls;
    var PanelBody = wp.components.PanelBody;
    var SelectControl = wp.components.SelectControl;
    var useSelect = wp.data.useSelect;
    var Fragment = wp.element.Fragment;

    wp.hooks.addFilter(
        'blocks.registerBlockType',
        'my-plugin/extend-all-products',
        function( settings, name ) {
            if ( name === 'woocommerce/all-products' ) {
                settings.attributes = Object.assign( settings.attributes, {
                    selectedCategory: {
                        type: 'string',
                        default: ''
                    }
                });
    
                var editFunction = settings.edit;
    
                settings.edit = function( props ) {
                    if (props.name === 'woocommerce/all-products') {
                        var categories = useSelect( function( select ) {
                            return select( 'core' ).getEntityRecords( 'taxonomy', 'product_cat', { per_page: -1 } ) || [];
                        }, [] );
    
                        var categoryOptions = categories.map( function( cat ) {
                            return { label: cat.name, value: cat.id };
                        } );
                        categoryOptions.unshift({ label: 'Select category', value: '' });
    
                        return el(
                            Fragment,
                            {},
                            el( editFunction, props ),
                            el(
                                InspectorControls,
                                {},
                                el(
                                    PanelBody,
                                    { title: 'Category Settings' },
                                    el(
                                        SelectControl,
                                        {
                                            label: 'Select Category',
                                            value: props.attributes.selectedCategory || '',
                                            options: categoryOptions,
                                            onChange: function( newValue ) {
                                                props.setAttributes({ selectedCategory: newValue });
                                            }
                                        }
                                    )
                                )
                            )
                        );
                    }
                    return el( editFunction, props );
                };
    
                settings.save = function() {
                    return null; // Gutenberg blocks usually return null for dynamic blocks.
                };
            }
            return settings;
        }
    );

    } )( window.wp );

    class Utilities_Function_Kategorie {

    public function __construct() {
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_category_filter_script'));
        add_filter('woocommerce_blocks_product_grid_query_args', array($this, 'filter_products_by_category'), 10, 2);
    }
    
    public function enqueue_category_filter_script() {
        wp_enqueue_script(
            'category-filter-block',
            plugins_url('category-filter.js', __FILE__),
            array('wp-blocks', 'wp-element', 'wp-components', 'wp-data', 'wp-editor'),
            filemtime(plugin_dir_path(__FILE__) . 'category-filter.js')
        );
    }
    
    public function filter_products_by_category($query_args, $attributes) {
        // Debugging logs
        error_log('Filtering products by category with attributes: ' . print_r($attributes, true));
    
        if (isset($attributes['selectedCategory']) && !empty($attributes['selectedCategory'])) {
            error_log('Selected category ID: ' . $attributes['selectedCategory']);
    
            // Ensure query is correctly updated
            $query_args['tax_query'][] = array(
                'taxonomy' => 'product_cat',
                'field'    => 'term_id', // Use 'term_id' instead of 'id' for taxonomy queries
                'terms'    => array($attributes['selectedCategory']),
                'operator' => 'IN',
            );
    
            error_log('Updated query_args with tax_query: ' . print_r($query_args, true));
        } else {
            error_log('No category selected or selectedCategory attribute is empty.');
        }
    
        return $query_args;
    }

    }

    new Utilities_Function_Kategorie();

    Thread Starter komar132

    (@komar132)

    Thank you very much for your response. I appreciate the help, but unfortunately, the situation hasn’t changed. I can now select a category from the product categories in the All Products block’s Inspector panel, but nothing happens after that. The products are not being filtered based on the selected category.

    I have tried logging the process, and it seems that the logs stop after selecting the category and saving it on the JavaScript side. However, no further action occurs beyond that point.

    Would you have any additional suggestions or ideas for why the filtering might not be working as expected?

    • This reply was modified 1 month, 3 weeks ago by komar132.
    Plugin Support Shameem R. a11n

    (@shameemreza)

    Hi @komar132

    Please note that writing or providing custom code is not within the scope of our support policy. If you are still having problems, we recommend asking development questions on the #developers channel of the WooCommerce Community Slack. Many of our developers hang out there and will be able to offer insights into your question. You can also seek help from the following:

    I wish I could help more, but hopefully, this gets you going in the right direction to get the job done.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.