How to Create a Dynamic Link to Parent Page


Sometimes you need to add extra navigation points to a website, such as a ‘back to X’ link, which is faster than requiring users to navigate through your main menu each time. If you only need to do this on one or two pages you can probably just hardcode the links as a workaround an no-one will know the difference. However, what if you have to do this on several pages? Even more specifically, what happens if you want to do this with user-generated content like in WordPress? Well, there’s a really simple bit of code that will get the job done:


<?php if ( $post->post_parent ): ?>
<a href="<?php echo get_permalink( $post->post_parent ); ?>" >
<?php echo get_the_title( $post->post_parent ); ?>
</a>
<?php endif; ?>

Just place the above code anywhere in your template files and it will automatically show the name of the parent page as a clickable hyperlink. It is also wrapped in an IF statement, so if there is no parent page the code will simply show nothing. Easy!