WordPress.org

Ready to get started?Download WordPress

Forums

get_category_link gives wrong URL (3 posts)

  1. sjspain
    Member
    Posted 2 years ago #

    I'm trying to create a page template that shows blog post underneath the main page. I'm trying to keep it general by getting the page page slug then finding blog posts from a category with a matching slug.

    I use get_category_by_slug() to get the category info. then use the term_id from that in get_category_link()

    BUT it returns the link for the page instead of the category archive.

    ../blog/catslug

    instead of

    ../blog/category/catslug

    Here's the code

    <?php
    get_template_part( 'loop', 'page' );
    
    $post_obj = $wp_query->get_queried_object();
    $post_name = $post_obj->post_name;
    query_posts( 'category_name='.$post_name );
    $this_cat = get_category_by_slug($post_name);
    ?>
    
    <h1 class="page-title"><a href="<?php esc_url(get_category_link( $this_cat->term_id )); ?>" title="More <?php echo $this_cat->cat_name; ?> posts from the blog archive" rel="bookmark">Recent <?php echo $this_cat->cat_name; ?>  posts from the blog</a></h3>
    
    <?php
    get_template_part( 'loop', 'category' );
    ?>

    I think this is a bug. Anybody got any suggestions?

  2. alchymyth
    Forum Moderator
    Posted 2 years ago #

    this might be happening is there is no matching category for the page slug.

    does the code output the correct category name in the h1 tag despite linking to the wrong page?

  3. sjspain
    Member
    Posted 2 years ago #

    Thanks alchymyth
    The slugs are definitely the same.

    The category and page name were the same so I hadn't checked that. I've now changed both names and can confirm that the code does output the correct category name in the h1 tag. It is only the link url that is wrong.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags