skip to Main Content

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.

2

Answers


  1. 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; ?>
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search