WordPress – how to get posts’s parent page?

I have set all my posts to a page called Work under Settings -> Reading.

And that I assume that now Work is the parent page of the posts.

Read More

So now I am trying to get the posts’ parent which is Work using this code,

print_r(get_permalink($post->post_parent));

But why can’t I view the data of this parent page? I get the current page’s data instead.

Any ideas?

EDIT:

single.php

<!-- container -->
<div class="container">

<?php
// Include the page nav.
get_template_part( 'nav-page', 'nav' );
?>

<?php
// Start the loop.
while ( have_posts() ) : the_post();

    /*
     * Include the post format-specific template for the content. If you want to
     * use this in a child theme, then include a file called called content-___.php
     * (where ___ is the post format) and that will be used instead.
     */
    get_template_part( 'content-single', get_post_format() );

// End the loop.
endwhile;
?>
</div>
<!-- container -->

content-single.php

<?php global $post;?>
<div id="wrapper">
    <div class="col-md-6">
        ///
    </div>
    <div class="col-md-6">
        <?php the_content(); ?>
        <?php
        var_dump($post->post_parent->ID);
        ?>
    </div>
</div>

Related posts

2 comments

  1. Since you have assigned a posts page, this is not a parent. Instead you must call:

    $blog_id = get_option('page_for_posts');
    get_permalink($blog_id);
    
  2. The issue here is that Work is not the parent page. You are setting the page Work to be the main page for the blog. The reason you are getting a 0 when you try to get the parent post ID is because there is not an actual parent of the Work page, as setting a page to the default reading page does not make it a parent page.

    If you were to create a page About and then set Work to be a child of that, you could use $parentID = $post->post_parent within the loop to retrieve the ID for the About page.

Comments are closed.