0

I'm looking for a way to change the widget title of Woocommerce Product Categories Widget based on the category I'm viewing.

Category 1 -----> Display Title of Widget for Category 1

- Sub Category
- Sub Category
- Sub Category

Category 2 -----> Display Title of Widget for Category 1

- Sub Category
- Sub Category
- Sub Category

I'm working with this but can't seem to target the widget title and create the if else statement correctly.

function retitle_woo_category_widget() {
    // If 'Category' 1 is being viewed...
    if ( is_product() && has_term( 'Category 1', 'product_cat' ) ) {
        //... Remove the images
        return __('Title of Widget for Category 1');
    }
    else {
    // If 'Category' 2 is being viewed...
    if ( is_product() && has_term( 'Category 2', 'product_cat' ) ) {
        return __('Title of Widget for Category 2');
}

add_filter ( 'widget_title' , 'retitle_woo_category_widget');

Any suggestions?

1
  • Your code has syntax error if and else block are not closed!
  • Also you are changing all widget title. Be specific to target only product category widget by checking for widget ID
  • Your current code will only effect if you are viewing single product page belongs to above categories. For all other pages return title as it is so title will not be blank.

Example:-

function retitle_woo_category_widget($title, $widet_instance, $widget_id) {

    if ( $widget_id !== 'woocommerce_product_categories' )
        return $title;

    // If 'Category' 1 is being viewed...
    if ( is_product() && has_term( 'Category 1', 'product_cat' ) ) {
        //... Remove the images
        return __('Title of Widget for Category 1');

    // If 'Category' 2 is being viewed...
    } else if ( is_product() && has_term( 'Category 2', 'product_cat' ) ) {
        return __('Title of Widget for Category 2');
    }

    return $title;
}
add_filter ( 'widget_title' , 'retitle_woo_category_widget', 10, 3);
  • Thanks. What does the 10, 3 mean at the very end? – thisisbolo Mar 16 '16 at 0:36
  • @thisisbolo 10 is priority of action and 3 is number of arguments to passed in callback function. Please continue reading Parameters for add_action – Sumit Mar 16 '16 at 4:42
  • @thisisbolo If answer works for us then we accept it, described here if not then we let answerer know what is the problem! – Sumit Mar 16 '16 at 4:52
  • I've tried these suggestions but this code doesn't produce any results. – thisisbolo Mar 17 '16 at 18:28
  • I've tested this answer, it is working fine. Perhaps you are not sure about the question. Good Luck :) – Sumit Mar 17 '16 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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