add code to display link in get category wordpress

I added this code to display the category list in the wordpress post, it only displays text, no link, how to display the category link. <?php $args = array( 'type' => 'post', 'number' => 1, 'parent' => ); $categories = get_categories( $args ); foreach ( $categories as $category ) { ?> <?php echo $category->name ; ?> <?php } ?> I added this code to display the category list in the wordpress post, it only displays text, no link, how to display the category link.

Comment (2)

Jese Leos

August 28, 2024

Verified user

To augment what you're doing you would simply get the category link before you echo the name and then close the link after the name, like this: <?php $args = array( 'type' => 'post', 'number' => 1, 'parent' => ); $categories = get_categories( $args ); foreach ( $categories as $category ) { echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">'; echo $category->name; echo '</a>'; } ?> You also don't need to keep opening and closing your PHP if you're just going to keep running new lines of PHP (ie. <?php ?>) I got the basic gist of my answer from: https://developer.wordpress.org/reference/functions/get_categories/ The documentation example is as follows: <?php $categories = get_categories( array( 'orderby' => 'name', 'order' => 'ASC' ) ); 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>'; } The output is formatted different but it's the same concept.

Jese Leos

August 28, 2024

Verified user

Oh my... Use get_category_link(): <?php $args = array( 'type' => 'post', 'number' => 1, 'parent' => 0, ); $categories = get_categories( $args ); foreach ( $categories as $category ) : ?> <a href="<?php echo get_category_link( ( int ) $category->term_id ); ?>"> <?php echo $category->name; ?> </a> <?php endforeach; ?>

You’ll be in good company