Home > Software engineering >  Simple way to remove anchor tags from wp_list_categories structure
Simple way to remove anchor tags from wp_list_categories structure

Time:02-22

I am using this simple solution to display all the sub-categories of an specific category with wordpress on archive page:

    <ul>
        <?php wp_list_categories( array(
            'orderby'            => 'id',
            'title_li'         => '',
            'use_desc_for_title' => false,
            'child_of'           => 15, // by industry
            'hide_empty'         => 0 
        ) ); ?>
    </ul>

The problem is that using this function I have undesired markup (links) pointing to each category/subcategory archive, which I don't want. Is there any simple solution to remove these links only? I tried with the get_terms way but it seems more complicate.

CodePudding user response:

You could use this to loop through the items manually.

get_categories( string|array $args = '' )

source: https://developer.wordpress.org/reference/functions/get_categories/

usage is as follows:

<?php
$categories = get_categories( array(
     'orderby'            => 'id',
     'title_li'         => '',
     'use_desc_for_title' => false,
     'child_of'           => 15, // by industry
     'hide_empty'         => 0 
) );
 
foreach( $categories as $category ) {
    $category_link = sprintf( 
        '<a href="%1$s" alt="%2$s">%3$s</a>',
        esc_url( get_category_link( $category->term_id ) ),
        esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
        esc_html( $category->name )
    );
     
    echo '<p>' . sprintf( esc_html__( 'Category: %s', 'textdomain' ), $category_link ) . '</p> ';
    echo '<p>' . sprintf( esc_html__( 'Description: %s', 'textdomain' ), $category->description ) . '</p>';
    echo '<p>' . sprintf( esc_html__( 'Post Count: %s', 'textdomain' ), $category->count ) . '</p>';
} 

Now you can create your own markup.

credits to @codex from the WP community for this code snippet.

  • Related