WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get page's parent's slug (post_name) (6 posts)

  1. B1gJ4k3
    Member
    Posted 3 years ago #

    Hi all, I've been having some trouble getting the slug (post_name) of a page's parent for some time now. I've figured out how to tell if a page is a child of another and all that, but all I can seem to get from that parent is its ID:

    $post_obj = $wp_query->get_queried_object();
    $post_name = $post_obj->post_name;
    $parent_name = $post->post_parent;

    This just returns the ID of the parent page, and I really need to return the slug.

    I have this function that does it elsewhere, but I can't see to make it work for the parent:

    function the_slug() {
    	$post_data = get_post($post->ID, ARRAY_A);
    	$slug = $post_data['post_name'];
    	return $slug;
    }

    Say I have a main page called "Welcome" with the slug "welcome" and a sub-page under Welcome that is called "Hello" with the slug "hello." I need to be able to use the value "welcome" when I'm on the page "Hello"

    Any help someone could provide would be much appreciated.

  2. caugb
    Member
    Posted 3 years ago #

    function the_parent_slug() {
      global $post;
      if($post->post_parent == 0) return '';
      $post_data = get_post($post->post_parent);
      return $post_data->post_name;
    }
  3. B1gJ4k3
    Member
    Posted 3 years ago #

    Nailed it. Exactly what I needed. Thanks!

  4. Nick Davis
    Member
    Posted 3 years ago #

    Hi caugb, thanks for this but I'm not sure how to get the output

    I put your code in the functions.php file and I thought I'd do something like

    echo $post_data

    to get the results, but I don't think that's it

    What should I be using to get the post parent's slug?

    Thanks

    Nick

  5. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    try either:

    <?php echo the_parent_slug(); ?>
    and add the function (from the reply by @caugb) into functions.php of your theme.

    or:

    <?php
    global $post;
    if($post->post_parent) { $post_data = get_post($post->post_parent);
    echo $post_data->post_name; }
    ?>
  6. Nick Davis
    Member
    Posted 3 years ago #

    Thanks alchymyth, that helped

Topic Closed

This topic has been closed to new replies.

About this Topic