Get the current category link (5 posts)

  1. gerardbm
    Posted 3 years ago #

    Hi! I'm trying to get the current category link because I want to show it into the Open Graph metadata. I'm using a function in functions.php, like this:

    If is_category, bla bla...

    <meta property="og:url" content="
      $the_cat = get_the_category();
      $category_link = get_category_link( $the_cat[0]->cat_ID );
    <?php echo $category_link ?>" />

    I have categories and subcategories. So it works right in a subcategory, for example domain.com/science/astrophysics/, but in the main category of science, it shows domain.com/science/astrophysics/ (because the last post of the loop is in the Astrophysics category.

    I wish the right URL for each category. Any help? Thanks.

  2. gerardbm
    Posted 3 years ago #

    I solved it adding a new function:

    function first_category_link() {
    	$category = get_the_category();
    	$category_link = get_category_link($category->term_id);
    	$parent = get_cat_name($category[0]->category_parent);
    	$parent_ID = get_cat_ID($parent);
    	$parent_link = get_category_link($parent_ID);
    	if ($parent_link) {
    		echo $parent_link;
    	} else {
    		echo $category_link;

    And this code:
    <?php first_category_link(); ?>

  3. Michael
    Part-Time Forum Moderator
    Posted 3 years ago #

    you seem to be doing this in a category archive page (If is_category, bla bla...)

    by using get_the_category() you are getting the categories of a post which can be quite random outside the loop;

    to get the category of the archive, use get_query_var('cat')

    $category_link = get_category_link( get_query_var('cat'));

  4. gerardbm
    Posted 3 years ago #

    Thanks @alchymyth. You're right. It took me four hours to find the function get_query_var('cat'). The use is outside the loop, so finally I did this code:

    $category_id = get_query_var('cat');
    echo get_category_link( $category_id );
  5. kiets
    Posted 3 years ago #

    thanks gerardbm!!!! spent days looking for a solution.

Topic Closed

This topic has been closed to new replies.

About this Topic