3

I am creating a little plugin and have troubles to find out how to create multiple category selection in my settings page. I am using multiple product selection like this which saves the selected values into options table:

<select class="wc-product-search" multiple="multiple" style="width: 50%;" id="namedayemail_options[exclude_prods]" name="namedayemail_options[exclude_prods][]" data-placeholder="<?php esc_attr_e( 'Search for a product&hellip;', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" >
    <?php
    if (isset($options['exclude_prods'])) {
        $ex_product_ids = $options['exclude_prods'];
        foreach ( $ex_product_ids as $product_id ) {
            $product = wc_get_product( $product_id );
            if ( is_object( $product ) ) {
                echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
            }
        }
    }
    ?>
</select> 

I am looking for similar solution for product categories.

I am sure LoicTheAztec will know the solution. Thanks ahead. :-)

1 Answer 1

2

You can get inspirations from Admin coupon edit page code:

<p class="form-field">
    <label for="namedayemail_options[exclude_cats]"><?php _e( 'Exclude categories', 'woocommerce' ); ?></label>
    <select id="namedayemail_options[exclude_cats]" name="namedayemail_options[exclude_cats][]" style="width: 50%;"  class="wc-enhanced-select" multiple="multiple" data-placeholder="<?php esc_attr_e( 'No categories', 'woocommerce' ); ?>">
    <?php
    $category_ids = $options['exclude_cats'];
    $categories   = get_terms( 'product_cat', 'orderby=name&hide_empty=0' );
    if ( $categories ) {
        foreach ( $categories as $cat ) {
            echo '<option value="' . esc_attr( $cat->term_id ) . '"' . wc_selected( $cat->term_id, $category_ids ) . '>' . esc_html( $cat->name ) . '</option>';
        }
    }
    ?>
    </select>
</p>

Maybe some adjustements will be required…

Sign up to request clarification or add additional context in comments.

1 Comment

As always, you are the best!! It works like a charm.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.