Customize WordPress widget – Product Category

Taking a look at the output rendered by the widget shows that the markup is missing a closing <a> tag for the term links and the widget instance does not have the closing </li>.

Viewing the page source and formatting the output makes it easier to identify these issues:

<li id="mdk_wpcat_widget-2" class="widget-container mdk_wpcat_widget">
  <h3 class="widget-title">Wooooo!</h3>

  <ul class="shop-categories">
    <li class="shop-category ">
      <a href="http://example.com/product-category/test-category-1/">
        <span class="bulletpoint"></span>
        <span class="category-title">Test Category 1</span>

    </li>

    <li class="shop-category ">
      <a href="http://example.com/product-category/test-category-1/test-subcategory-1/">
        <span class="bulletpoint"></span>
        <span class="category-title">Test Subcategory 1</span>

    </li>
  </ul>

Here’s a an updated version of the code that outputs the HTML. The formatting has been improved and the missing closing anchor tag has been fixed. Keeping things nicely formatted helps to identify errors.

$count = count( $product_categories );
if ( $count > 0 ) {
  echo '<ul class="shop-categories">';

  foreach ( $product_categories as $product_category ) {
    $active_cat = $product_category->name == single_cat_title( '', false ) ? ' active-cat' : '';
    echo '
      <li class="shop-category' . $active_cat . '">' .
        '<a href="' . esc_url( get_term_link( $product_category ) ) . '">' .
          '<span class="bulletpoint"></span>' .
          '<span class="category-title">' . esc_html( $product_category->name ) . '</span>' .
        '</a>' .
      '</li>';
  }

  echo '</ul>';
}

The missing closing </li> tag for the widget instance is caused from overwriting the $args array with the arguments passed to get_terms(). This causes echo $args['after_widget']; to throw a warning. Always turn on error reporting when developing.

Create a separate array for the arguments passed to get_terms():

// Custom Woo Category Output
$get_terms_args = array(
    'number'     => $number,
    'orderby'    => 'menu_order',
    'order'      => 'ASC',
    'hide_empty' => $hide_empty,
    'include'    => $ids,
    'exclude'    => '72', //Hides "film" category by ID
);

$product_categories = get_terms( 'product_cat', $get_terms_args );

Note that $number, $hide_empty, and $ids are all undefined too, so those variables should be properly initialized.