Get title of page from URL

I have a “Go back button”:

$url = htmlspecialchars( $_SERVER['HTTP_REFERER'] );
echo "<a href="https://wordpress.stackexchange.com/questions/211840/$url">back</a>";

I need to display the page title of the $url, something like this:

$url = htmlspecialchars( $_SERVER['HTTP_REFERER'] );
echo "<a href="https://wordpress.stackexchange.com/questions/211840/$url">Go back to the INSERT PAGE TITLE HERE</a>";

Does anyone know how to do this?

1 Answer
1

WordPress has a function called url_to_postid that may work in this situation. You can try the following (untested):

<?php
    $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
    $back_id = url_to_postid($_SERVER['HTTP_REFERER']);
    if( $back_id > 0 ){
         $back_title = get_the_title( $back_id );
         echo "<a href="https://wordpress.stackexchange.com/questions/211840/{$url}">Go back to the {$back_title}</a>"; 
    }

Leave a Comment