I have a weird problem: When I echo the $post->post_name on the top of the page, I see the slug of the first post that appears in the loop in the body of the page and not the page’s slug. Why is this happening and how can I get the current page’s slug?

[ad_1]

Hi

I have 3 pages: Home, Discounts (archive page of discount CPT) and Contact. When I echo out the post\_name on the Home and Contact pages, I get the page’s slug but on the Discounts page, it outputs the slug of the first post that appears in the loop in the main tag. Why is this happening?

What I’m trying to achieve is to add the .active class name to the current page’s nav menu and I saw online that I need to check the post\_name. Is there any other better way of doing this? (my menu is handcoded, not going from WP’s Menus page).

Thanks

[ad_2]
2 Comments
  1. You could try **echo single_post_title();**

    I had the same problem with the blog page, it would echo the latest post title in the page meta title. This fixed it though, so may work for you.

  2. In no uncertain terms, its because on any given page a default loop consists of that pages information. On an archive page the default loop is all the posts.

    You should be using get_the_title() for post titles but regardless this will still not work on an archive page.

    You can get the title from get_queried_object() which looks up the current rendered page. You should be able to do

    <?php $page = get_queried_object() ; echo $page->title;?>

    But I don’t know what the title is in the array without checking, if you want to see what it’s listed inside the array do.

    <?php print_r($page) ;? >

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer