Only Show One Category Name Per Post

I wrote a function to only show a limited number of recent posts per page, and it works fine. But I also want to display only one category-name per post (even if the post has several others), I just want it display the first [0] category from each post.

I've spend hours on this and I've gotten very close, but just end up with the posts showing all categories on a list, like when using ?php the_category(" "); ?

I got very close with the code below, which only displays the first category name of each post, but I can't make it echo out the permalink to the category also, only the text string :-/

?php

            $query = new WP_Query(array(
             'posts_per_page'   = 2,
             'categories_per_page' = 1  
    ));

    while ($query-have_posts()): $query-the_post(); ?
            lia href="?php the_permalink(); ?"?php the_title(); ?/a/li

          !-- Gets category name but not the link --
            ?php $category = get_the_category(); 
                echo $category[0]-cat_name; ?       

    ?php endwhile; ? 

I've read everything I could find on the topic on: https://codex.wordpress.org/Function_Reference/get_category_link https://developer.wordpress.org/reference/functions/wp_list_categories/

I've tried wrapping it inside a permalink, but I keep getting errors. Can someone help me out? :-)

Topic functions Wordpress

Category Web


You need to pass the category ID into get_category_link()

<a href="<?php echo esc_url( get_category_link( $category[0]->term_id ) ); ?>"><?php echo $category[0]->cat_name; ?></a>

Here's the whole thing put together

<?php
$query = new WP_Query( array(
  'posts_per_page'      => 2,
  'categories_per_page' => 1,
) );

while ( $query->have_posts() ) : $query->the_post(); ?>

  <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

  <?php
  $category = get_the_category();

  if ( ! empty( $category ) ) {
  ?>
    <a href="<?php echo esc_url( get_category_link( $category[0]->term_id ) ); ?>"><?php echo $category[0]->cat_name; ?></a>
  <?php
  }

endwhile;
?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.