Skip to content

Instantly share code, notes, and snippets.

@GiannisRallis
Last active August 31, 2023 07:46
Show Gist options
  • Save GiannisRallis/e8152cb307a3a27d528d742ff0d4392c to your computer and use it in GitHub Desktop.
Save GiannisRallis/e8152cb307a3a27d528d742ff0d4392c to your computer and use it in GitHub Desktop.
PMPro Redirect After Checkout to last visited URL
<?php
/**
* Paste the Code inside function.php file or use Code Snipet .
*/
/**
* Store the last URL visited on each page load.
*/
function my_pmpro_redirect_to_referring_page_after_checkout_track() {
if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
$last_url_viewed = $_SERVER['HTTP_REFERER'];
global $post, $pmpro_pages;
// Do not track the URL if we are on one of the PMPro pages.
if ( $post && $pmpro_pages && in_array( strval( url_to_postid( $last_url_viewed ) ), $pmpro_pages, true ) ) {
return;
}
// Set a cookie to store the last URL before checkout
setcookie( 'my_pmpro_last_url_before_checkout', $last_url_viewed, time() + 3600, '/' );
}
}
add_action( 'wp', 'my_pmpro_redirect_to_referring_page_after_checkout_track' );
/**
* Redirect to last page instead of confirmation page after checkout.
*
* @param string $url The confirmation page URL to redirect to.
*
* @return string The updated confirmation page URL to redirect to.
*/
function my_pmpro_redirect_to_referring_page_after_checkout_redirect( $url ) {
if ( isset( $_COOKIE['my_pmpro_last_url_before_checkout'] ) ) {
$last_url = $_COOKIE['my_pmpro_last_url_before_checkout'];
// Check if the last URL is safe and return it for redirection
if ( wp_http_validate_url( $last_url ) ) {
return $last_url;
}
}
// If there's no valid last URL, return the original confirmation URL
return $url;
}
/**
* Add filter to redirect user after checkout.
*/
function my_pmpro_redirect_to_referring_page_after_checkout_filter() {
add_filter( 'pmpro_confirmation_url', 'my_pmpro_redirect_to_referring_page_after_checkout_redirect' );
}
add_action( 'init', 'my_pmpro_redirect_to_referring_page_after_checkout_filter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment