Term Checklist Walker – Disable Parent Categories

Edited because I had completely misread question.


To know if term is a parent or not, we need access to term post parent, so is better to replace more specialized methods istead of walk().

That said, I understand that code in OP uses class definition inside the function to avoid fatal error because of Walker_Category_Checklist class not defined, however code becomes hardly readable in that way.

So I think is better write a custom function that return an instance of the custom walker:

add_filter( 'wp_terms_checklist_args', 'wpse_149328_set_walker' );  

function wpse_149328_set_walker( $args ) {
  if (
    ! empty( $args['taxonomy'] )
    && ( $args['taxonomy'] === 'product_cat' ) // only for 'product_cat' taxonomy
    && ( ! isset( $args['walker'] ) || ! $args['walker'] instanceof Walker )
  ) {
    $args['checked_ontop'] = FALSE;
    $args['walker'] = get_Walker_Category_No_Parent();
  }
  return $args;
}

now let’s code the get_Walker_Category_No_Parent() and the custom walker:

function get_Walker_Category_No_Parent() {

  class Walker_Category_No_Parent extends Walker_Category_Checklist {

   function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
      if ( (int) $category->parent === 0 ) {
         $this->doing_parent = esc_html( $category->name );
      } else {
        parent::start_el( $output, $category, $depth, $args, $id );
      }
    }

    function end_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
      if ( ! isset( $this->doing_parent ) || empty( $this->doing_parent ) ) {
        parent::end_el( $output, $category, $depth, $args, $id );
      }
    }

    function start_lvl( &$output, $depth = 0, $args = array() ) {
      if ( isset( $this->doing_parent ) && ! empty( $this->doing_parent ) ) {
        $output .= '<li><strong>' . $this->doing_parent . '</strong></li>';
        $this->doing_parent = FALSE;
      }
      parent::start_lvl( $output, $depth = 0, $args );
    }

  }
  return new Walker_Category_No_Parent;
}

This walker output parent categories as text and only if they have some children.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)