I need some help. I am trying to prevent direct access to a page that my customers get redirected to after checkout. I want the page to be accessible only after checkout.
I have found this topic: https://wordpress.stackexchange.com/questions/290234/prevent-block-direct-access-to-a-thank-you-page
I placed the following code snippet to my functions.php:
add_action('template_redirect', function() {
// ID of the redirect page
if (!is_page(2072)) {
return;
}
// URL of checkout page
if (wp_get_referer() === 'https://www.exampledomain.com/checkout/') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
} );
This works fine if the customer pays through Stripe. However, it does not work if the customer chooses to pay through PayPal because PayPal redirects the customer to their website to make the payment.
Can something be done here to fix this issue?
You could do it the other way around. Only accept an array of predefined urls. For example here we have defined an array with github and stackoverflow as referees. If the referring url isn't one of those two, then we kill the process. With wp_die() we can display a custom message and a backlink, and with header() we can redirect automatically after 3 seconds.
add_action( 'wp', function() {
if( is_page( '3975' ) && ! is_admin() ) { // restrict page ID '2072' if it's on the front end and if user doesn't have the permissions
$base = [ // allowed referees
'https://github.com/', // referee 1
'https://stackoverflow.com/', // referee 1 ... and so on
];
if( ! in_array( $_SERVER['HTTP_REFERER'], $base ) ) { // if not in referees
header( 'Refresh: 3; ' . esc_url( home_url() ) ); // redirect in 3 seconds
wp_die( 'Something went wrong.', NULL, $args = array( 'back_link' => true, ) ); // kills WordPress execution and displays an HTML page with an error message
exit; // terminate the current script
};
};
} );
I've had a look at a bunch of things. wp_get_referer() can't be used that way as it's specific to Wordpress
Retrieve referer from _wp_http_referer or HTTP referer. If it’s the same as the current request URL, will return false.
I'm using $_SERVER['HTTP_REFERER'] instead # https://stackoverflow.com/a/16374737/3645650. Which does the job I thaught wp_get_referer() would do.
Related
I have the following function which redirects people to an age verification page if their session has expired:
function age_verification() {
global $wp_session;
if (is_admin())
return false;
$isAgeVerification = is_page('age-verification');
$isAgeVerification = strpos($_SERVER['REQUEST_URI'], 'age-verification') !== false;
if(!$isAgeVerification && $wp_session['age_allow'] == 0)
{
wp_safe_redirect( '/age-verification/' );
exit;
}
if($isAgeVerification && $wp_session['age_allow'] == 1)
{
wp_safe_redirect( '/' );
exit;
}
}
add_action( 'init', 'age_verification' );
How do I get them to be redirected back to the the page they typed into the address bar originally? I've tried to capture $_SERVER['REQUEST_URI'] but it gives me the current /age-verification page and not the page they were referred from. I also tried $_SERVER['HTTP_REFERER'] but it is not set...
Is this possible with my current function? Thanks!
EDIT:
So whenever I call $_SERVER['REQUEST_URI'] I get the page that the browser is redirecting to (domain.com/age-verification). However, I've noticed that if I put an exit; immediately after my $_SERVER['REQUEST_URI'], I get the correct result. It's almost as if $_SERVER['REQUEST_URI'] is too slow and gets updated with domain.com/age-verification before it has a chance to get the current page before redirection...
Does that offer any more clues? What else can I provide to help out on this?
You could set the current REQUEST_URI to the Session before redirecting to age verification and use this value for redirecting back.
Another possibility is to put it in a URL Parameter when redirecting to age verification.
I'm making an advertisement service, I'm using wordpress template. It works fine, but from a week I realise that I've a problem, I don't know when I destroy something.
When I'll post new ad the page is checking if am I logged in.
if ( !is_user_logged_in() ) {
$login = $redux_demo['login'];
wp_redirect( $login ); exit;
} else {
}
And mostly it redirect me into Login page (I'm logged in).
On the Login page it checks:
if ( is_user_logged_in() ) {
global $redux_demo;
$profile = $redux_demo['profile'];
wp_redirect( $profile ); exit;
}
And it is redirecting me into Profile page! So in the first time it return that I'm not logged in, but on the second page it return that I'm logged in.
Sometimes it works. For example when I login and wait a few minutes it works correctly, but when I sign out and login there's the same problem. Do you have some ideas how to fix it?
The best practice for redirecting is to use the WordPress action event hook called template_redirect. This event ensures that you are:
Checking for the user's login state after that information is available (i.e. and not too early in the load process)
WordPress is ready to accept a redirect
In your use case, you would want to do the following:
add_action('template_redirect', 'redirect_to_login_page_if_not_logged_in');
/**
* Redirect to the login page if the user is not logged in.
*
* #since 1.0.0
*
* #return void
*/
function redirect_to_login_page_if_not_logged_in() {
if ( is_user_logged_in() ) {
return;
}
global $redux_demo;
if ( isset( $redux_demo['login'] ) ) {
wp_redirect( esc_url( $redux_demo['login'] ) );
exit();
}
// Redirect to the built-in WordPress login page
auth_redirect();
}
If the user is logged in, just bail out (with the return). Else, check if the 'login' key is set in your global variable. If yes, redirect to that page. Else, redirect to the built-in WordPress login page using auth_redirect().
I am trying to add a custom URL structure to a WordPress based website.
for example:
example.com/machines //list all machines in a table
example.com/machines?some=params //list filtered machines in a table
example.com/machines/1 //show single machine
The data will come from an external api i have already developed, via curl.
I cannot import the data into a custom post type as it is normalized over many tables, the business logic is complicated and the api is used by other devices anyway.
I have looked at the docs for add_rewrite_rule, but the second parameter has me stumped:
$redirect
(string) (required) The URL you would like to actually fetch
Well I don't have a url to fetch, I want to run a function, that will act as a simple router - take the url parts, call the external api and return a template with the correct data.
Calling the API will be simple, but how i actually route the url to the function, and how I then load a template (utilizing existing WordPress header.php and footer.php) has me stumped.
After much googling and reading a few good resources, I have found the solution.
Step 1: Use add_rewrite_endpoint to create a base url that will be mapped to a query variable:
add_action( 'init', function(){
add_rewrite_endpoint( 'machines', EP_ROOT );
} );
Step 2: Visit the permalinks settings page and click "Save Changes" to flush the rewrite rules.
Step 3: Hook into the action 'template_redirect' to actually do something when the url is hit:
add_action( 'template_redirect', function() {
if ( $machinesUrl = get_query_var( 'machines' ) ) {
// var_dump($machinesUrl, $_GET);
// $machinesURl contains the url part after example.com/machines
// e.g. if url is example.com/machines/some/thing/else
// then $machinesUrl == 'some/thing/else'
// and params can be retrieved via $_GET
// after parsing url and calling api, it's just a matter of loading a template:
locate_template( 'singe-machine.php', TRUE, TRUE );
// then stop processing
die();
}
});
Step 4: The only other thing to do is handle a hit to a url with no further parts to it e.g. example.com/machines.
It turns out that at some point within WordPress's guts, the empty string gets evaluated to false and thus skipped, so the final step is to hook into the filter 'request' and set a default value:
add_filter( 'request', function( $vars = [] ) {
if ( isset( $vars['machines'] ) && empty( $vars['machines'] ) ) {
$vars['machines'] = 'default';
}
return $vars;
});
This can easily be improved by wrapping it all in a class(es).
The url parsing and template loading logic can be passed to a basic router, even a rudimentary MVC setup, loading routes from a file etc, but the above is the starting point.
A simplier solution is to just create a new template redirect.
So assuming you loading example.com/custom-url
/**
* Process the requests that comes to custom url.
*/
function process_request() {
// Check if we're on the correct url
global $wp;
$current_slug = add_query_arg( array(), $wp->request );
if($current_slug !== 'custom-url') {
return false;
}
// Check if it's a valid request.
$nonce = filter_input(INPUT_GET, '_wpnonce', FILTER_SANITIZE_STRING);
if ( ! wp_verify_nonce( $nonce, 'NONCE_KEY')) {
die( __( 'Security check', 'textdomain' ) );
}
// Do your stuff here
//
die('Process completed' );
}
add_action( 'template_redirect', 'process_request', 0);
I'm using WordPress and I want the user to go to the Home Page on their first visit, but on every other visit after that I would like them to be redirected to the Blog.
Home Page:
www.website.com
Blog:
www.website.com/blog
I'm guessing the best way to do this is to set a cookie?
I have no idea on what PHP files to edit or anything...
In your theme functions.php ( or plugin )
function o99_set_newvisitor_cookie() {
if ( !is_admin() && !isset($_COOKIE['sitename_newvisitor'])) {
setcookie('sitename_newvisitor', 1, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);
}
}
add_action( 'init', 'o99_set_newvisitor_cookie');
After that
if (isset($_COOKIE['sitename_newvisitor'])) {
echo 'Welcome back!'; // or redirect using wp_redirect( 'some_url/' ); exit;
}
else {
echo 'Hello new visitor!'; // or redirect using wp_redirect( home_url() ); exit;
}
This should do the job .
Wordpress itself had a function called wp_setcookie() but it was deprecated and replaced by wp_set_auth_cookie() which is only for user auth I believe . Not sure why, but maybe because of cookies laws that were introduced ( and that also you need to take into account )
Anyhow, see also the normal PHP setcookie() docs and the wp_redierct() function in codex.
I render login form on my header template using this code:
<?php wp_login_form($args); ?>
When I pass proper credentials, it redirect me to homapage and all seems to be fine, but when I put wrong login or pass, it redirect me to the folowing url:
http://localhost/wordpress/wp-login.php
So the question is how I can output errors on the same page , and prevent redirection to the wp-login ? I try to find solution but didnt have any results. Thanks!
Add this to your functions.php :
add_action( 'wp_login_failed', 'my_front_end_login_fail' ); // hook failed login
function my_front_end_login_fail( $username ) {
$referrer = $_SERVER['HTTP_REFERER']; // where did the post submission come from?
// if there's a valid referrer, and it's not the default log-in screen
if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
wp_redirect( $referrer . '?login=failed' ); // let's append some information (login=failed) to the URL for the theme to use
exit;
}
}
This code redirects to the same page as the user tries to log in from.
Change $referrer for another page.
Hope it will works for you.