admin管理员组

文章数量:1278910

I am still learning but I wasnt able to style a category link. I was able to create the following so only 1 category link is displayed. But I was unsure how I can modify this so I can add a class and style it. Is anyone able to help?

            <?php 
             // category link   
$categories = get_the_category();
        if ( ! empty( $categories ) ) {
echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) 
      ) . '">' . esc_html( $categories[0]->name ) . '</a>';
      }
    // category link
         ?>

I am still learning but I wasnt able to style a category link. I was able to create the following so only 1 category link is displayed. But I was unsure how I can modify this so I can add a class and style it. Is anyone able to help?

            <?php 
             // category link   
$categories = get_the_category();
        if ( ! empty( $categories ) ) {
echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) 
      ) . '">' . esc_html( $categories[0]->name ) . '</a>';
      }
    // category link
         ?>
Share Improve this question asked Sep 23, 2021 at 7:40 Gmad Gmad 1 2
  • 1 You've got HTML right there <a href=". Just add a class to it. – Jacob Peattie Commented Sep 23, 2021 at 7:44
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Bot Commented Sep 29, 2021 at 20:43
Add a comment  | 

1 Answer 1

Reset to default 0

Here is an example of how you can do it with your code, using the category name as the class name:

<?php 
             // category link   
$categories = get_the_category();
        if ( ! empty( $categories ) ) {
echo '<a class="' .esc_html( $categories[0]->name ) . '" href="' . esc_url( get_category_link( $categories[0]->term_id ) 
      ) . '">' . esc_html( $categories[0]->name ) . '</a>';
      }
    // category link
         ?>

本文标签: phpStyling a category link