Support » Fixing WordPress » Get the current category link

  • 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, but in the main category of science, it shows (because the last post of the loop is in the Astrophysics category.

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

Viewing 4 replies - 1 through 4 (of 4 total)
  • 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(); ?>



    Forum Moderator

    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'));

    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 );

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

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Get the current category link’ is closed to new replies.