简体   繁体   中英

How to catch a URL parameter and display a custom page title in wordpress

As a novice , I asked this to lots of paid developers who either said No or quoted exorbitant price or said Not achievable .

But I have achieved few thing on my site by going through all the interactions here. So thought of taking a second opinion.

A custom gateway payment plugin returns to Woocommerce Thank you page , if the transaction is successful but returns to a normal wordpress page -failed-payment, if payment is unsuccessful.

For the unsuccessful payment the return URL is :

mysite.com/failed-payment/?b_name=Jack.

On the failed-payment page, I want to display a personalised Page Title as Sorry, Jack, Your payment was unsuccessful.

Creating a new page template or modifying page template file is not an option. Has to be done via theme function. php .

To write the page title , I have thought of the following to be written in theme function. php :

   function assignPageTitle( $title ){
        if ( is_page(3062) ) {
          $title = sprintf("Sorry, %s, Your payment was unnsuccessful", b_name);
    }

    return $title;
    }
    add_filter('wp_title', 'assignPageTitle');

Is it achievable or impossible ? If achievable , how should I approach doing it??

Thanks.

To catch b_name from URL parameter and assign it to php variable is as following:

$b_name = $_GET['b_name'];

Now you can use it in your code eg:

$title = sprintf("Sorry, %s, Your payment was unnsuccessful", $b_name);

Also I will modify your code a little bit to alter title only when b_name is available (note: I have not tested your WP code so using as it is:)

function assignPageTitle( $title ){
    if ( is_page(3062) && isset($_GET['b_name']) ) {

  $b_name = $_GET['b_name'];
 $title = sprintf("Sorry, %s, Your payment was unnsuccessful", $b_name);
}

return $title;
}
add_filter('wp_title', 'assignPageTitle');

See, how I have added condition isset() for GET parameter, so that it tries to alter page title only when ?b_name= is available in the url.

By below code put into your theme function.php you can modify titles of your page without change / modify any template files:

//modify page title:
function assignPageTitle($title){
    $title = $_GET['b_name'];
    if ( is_page(3062) ) {
        return $title;    
    }
    else{
        return $title;
    }
}
add_filter('pre_get_document_title', 'assignPageTitle');

//Modify entry title 
add_filter( 'the_title', 'suppress_title', 10, 2 );
function suppress_title($title, $id = null){
    $b_name = $_GET['title'];
    if ( is_page(3062) ) {
          $title = sprintf("Sorry, %s, Your payment was unnsuccessful", $b_name);
    }    
    return $title;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM