JacobTheDev
JacobTheDev

Reputation: 18520

How do I get the parent post's URL in WordPress?

In WordPress How can I get the URL of the parent post (for a kind of Up button)?

This is the code I'm using to pull the parent name:

<?php 
    if( empty($wp_query->post->post_parent) ) {
        $parent_post_id = $wp_query->post->ID;
    } else {
        $parent_post_id = $wp_query->post->post_parent;
    }
    $parent_post = get_post($parent_post_id); 
    $parent_post_title = $parent_post->post_title; 
    echo $parent_post_title; 

Upvotes: 1

Views: 8203

Answers (2)

blizzrdof77
blizzrdof77

Reputation: 383

This is an alternate method I use, which gets the parent page permalink based on the current permalink path instead of the $post->page_parent property:

/**
 * Get the parent permalink based on the url path
 *
 * @param $id int
 * @return str
 */
function get_parent_permalink($id = false) {
    $id = !$id ? get_the_id() : $id;
    return str_replace(basename(get_permalink($id)) . '/', '', get_permalink($id));
}

Upvotes: 1

ninja
ninja

Reputation: 2263

Use get_permalink($postid):

global $post;

$parentId = $post->post_parent;
$linkToParent = get_permalink($parentId);

Upvotes: 8

Related Questions