I am trying to use below code that whenever user goes to page name called "Through Phone Call" it should direct him to certain page
In functions.php
function my_custom_add_to_cart_redirect( $url ) {
$page_title = $post->post_title;
if ($page_title == "Through Phone Call") {
$url = get_permalink( 2855 );
} else {
$url = get_permalink( 1853 );
}
}
But the code is not functioning what i am missing?
According to the docs you need to call wp_redirect() like below:
function my_custom_add_to_cart_redirect( $url ) {
$page_title = $post->post_title;
if ($page_title == "Through Phone Call") {
$url = get_permalink( 2855 );
} else {
$url = get_permalink( 1853 );
}
wp_redirect( $url );
exit;
}
Related
I'm trying to build a little web application on WordPress that will take a URL and list all redirects that it generates, but I'm running into issues where some sites state to use curl, some wp_remote_head, some get_header, and others file_get_contents but none are working well at all. I'm also seeing that some headers may pass "location" and others "Location".
Additional: Because it's using WordPress, I'm calling this function via Ajax and then setting the results in a transient so that if someone bombards the page, it doesn't kill my site. I have another function that looks for "error" and updates a status div. The resulting unordered list is displayed in a results div.
Problem: It's not listing the redirects, it always shows that no redirect was found.
Ultimately, I'd like traceredirects to respond with:
Origin: http://marketingtechblog.com
Redirect (301): http://martech.zone
Redirect (301): https://martech.zone
Destination (200): https://martech.zone
function traceredirects() {
check_ajax_referer( 'traceredirects_nonce', 'nonce' );
$url = $_POST['url'];
$valid_url = filter_var($url, FILTER_VALIDATE_URL);
if (!$valid_url) {
echo '<strong>Error:</strong> Please enter a valid URL with http:// or https://';
wp_die();
}
$host = parse_url($url, PHP_URL_HOST);
if(!checkdnsrr($host, 'ANY')) {
echo '<strong>Error:</strong> Could not find the domain ' . $host;
wp_die();
}
$transient_name = $url . '_traceredirect';
$traced = get_transient( $transient_name );
if (false === $traced) {
$args = array(
'redirection' => 10, // follow up to 10 redirects
);
$redirects = array();
$redirects[] = $url;
$response = wp_remote_get( $url, $args );
$headers = wp_remote_retrieve_headers( $response );
$http_code = wp_remote_retrieve_response_code( $response );
$traced = '<ul>';
if ( ! is_wp_error( $response ) ) {
if (!isset($headers['location'])) {
$traced .= '<li>No redirects found</li>';
} else {
while (isset($headers['location'])) {
if ( in_array( $headers['location'], $redirects ) ) {
echo 'Error: Redirect loop detected';
break;
}
$redirects[] = $headers['location'];
$response = wp_remote_get( $headers['location'], $args );
$headers = wp_remote_retrieve_headers( $response );
$http_code = wp_remote_retrieve_response_code( $response );
$traced .= '<li>HTTP code: ' . $http_code . ', URL: ' . $headers['location'] . '</li>';
}
}
} else {
echo 'Error: ' . $response->get_error_message();
wp_die();
}
$traced .= '</ul>';
set_transient( $transient_name, $traced, HOUR_IN_SECONDS );
}
echo $traced;
wp_die();
}
add_action( 'wp_ajax_traceredirects', 'traceredirects' );
add_action( 'wp_ajax_nopriv_traceredirects', 'traceredirects' );
I've been searching for plugins and snippets which would handle it for hours, but no success. Every single answer doesn't work for me. I have "Log in" link in menu, leading to WooCommerce "My account" page, which shows login form. I want customers to return to page where "Log in" link was clicked after successful login.
wp_get_referer() doesn't return anything and $_SERVER["HTTP_REFERER"] returns my account page if put within function hooked to woocommerce_login_redirect (I used PHP debug console to check).
Here is my code:
// Redirect user after login.
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
function wc_custom_user_redirect( $redirect, $user ) {
// Get the first of all the roles assigned to the user
$role = $user->roles[0];
$dashboard = admin_url();
if (in_array($role, array('administrator', 'shop_manager', 'editor', 'author', 'contributor'))) {
$redirect = $dashboard;
} elseif (in_array($role, array('customer', 'subscriber'))) {
$redirect = $_SERVER["HTTP_REFERER"];
} else {
$redirect = $_SERVER["HTTP_REFERER"];
}
return $redirect;
}
Here is where filter which I used appears in WooCommerce code:
/**
* Process the login form.
*/
public static function process_login() {
$nonce_value = isset( $_POST['_wpnonce'] ) ? $_POST['_wpnonce'] : '';
$nonce_value = isset( $_POST['woocommerce-login-nonce'] ) ? $_POST['woocommerce-login-nonce'] : $nonce_value;
if ( ! empty( $_POST['login'] ) && wp_verify_nonce( $nonce_value, 'woocommerce-login' ) ) {
try {
$creds = array(
'user_password' => $_POST['password'],
'remember' => isset( $_POST['rememberme'] ),
);
$username = trim( $_POST['username'] );
$validation_error = new WP_Error();
$validation_error = apply_filters( 'woocommerce_process_login_errors', $validation_error, $_POST['username'], $_POST['password'] );
if ( $validation_error->get_error_code() ) {
throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . $validation_error->get_error_message() );
}
if ( empty( $username ) ) {
throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . __( 'Username is required.', 'woocommerce' ) );
}
if ( is_email( $username ) && apply_filters( 'woocommerce_get_username_from_email', true ) ) {
$user = get_user_by( 'email', $username );
if ( isset( $user->user_login ) ) {
$creds['user_login'] = $user->user_login;
} else {
throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . __( 'A user could not be found with this email address.', 'woocommerce' ) );
}
} else {
$creds['user_login'] = $username;
}
// On multisite, ensure user exists on current site, if not add them before allowing login.
if ( is_multisite() ) {
$user_data = get_user_by( 'login', $username );
if ( $user_data && ! is_user_member_of_blog( $user_data->ID, get_current_blog_id() ) ) {
add_user_to_blog( get_current_blog_id(), $user_data->ID, 'customer' );
}
}
// Perform the login
$user = wp_signon( apply_filters( 'woocommerce_login_credentials', $creds ), is_ssl() );
if ( is_wp_error( $user ) ) {
$message = $user->get_error_message();
$message = str_replace( '<strong>' . esc_html( $creds['user_login'] ) . '</strong>', '<strong>' . esc_html( $username ) . '</strong>', $message );
throw new Exception( $message );
} else {
if ( ! empty( $_POST['redirect'] ) ) {
$redirect = $_POST['redirect'];
} elseif ( wp_get_referer() ) {
$redirect = wp_get_referer();
} else {
$redirect = wc_get_page_permalink( 'myaccount' );
}
wp_redirect( apply_filters( 'woocommerce_login_redirect', $redirect, $user ) );
exit;
}
} catch ( Exception $e ) {
wc_add_notice( apply_filters( 'login_errors', $e->getMessage() ), 'error' );
do_action( 'woocommerce_login_failed' );
}
}
}
I tried the answer of #dineshkashera but it throws an error as starting a session is not a good practice and also wp_get_referer hook is not working and thus $_SERVER['HTTP_REFERER'].
So my only solution is creating a cookie that will save our previous link.
Here's my Code:
//First we need to set a cookie that will save the previous url
setcookie('nlcrc', $_SERVER['HTTP_REFERER'], time() + 86000, COOKIEPATH, COOKIE_DOMAIN, false);
//Then initiate Woocommerce redirect hook
//This is for the WC login redirect
add_filter('woocommerce_login_redirect', 'wcc_redirects', 9999, 2);
//I have added also WC registration redirect
add_filter('woocommerce_registration_redirect', 'wcc_redirects', 9999, 1);
//Then this will be the handler
function wcc_redirects ($redirect) {
if (isset($_COOKIE['nlcrc'])) {
$redirect = $_COOKIE['nlcrc'];
return $redirect;
} else {
$redirect = home_url();
return $redirect;
}
}
or you can also somewhat quick and dirty with Javascript. If your default login page is Woocommerce My Account Page.
add_filter('woocommerce_login_redirect', 'wc_cstm_login_redirect', 99 );
function wc_cstm_login_redirect () {
echo "<script type='text/javascript'>
history.go(-2);
</script>";
}
Please try the below code, i hope it helps you.
Paste the below code in current active theme functions.php file.
// start global session for saving the referer url
function start_session() {
if(!session_id()) {
session_start();
}
}
add_action('init', 'start_session', 1);
// get referer url and save it
function redirect_url() {
if (! is_user_logged_in()) {
$_SESSION['referer_url'] = wp_get_referer();
} else {
session_destroy();
}
}
add_action( 'template_redirect', 'redirect_url' );
//login redirect
function login_redirect() {
if (isset($_SESSION['referer_url'])) {
wp_redirect($_SESSION['referer_url']);
} else {
wp_redirect(home_url());
}
}
add_filter('woocommerce_login_redirect', 'login_redirect', 1100, 2);
We have to use WordPress referrer function:
For example, set referrer URL in session or hidden field by clicking on add to cart button or any button to store previous URL. Once login or register success add WooCommerce success login redirect to that URL.
Read about the Referrer function.
Here's an answer about the WooCommerce login redirect.
this will solve your prolem
add_filter( 'woocommerce_login_redirect', function(){
wp_safe_redirect(wp_get_referer());
}, 10, 2 );
We use WordPress and would like to link amp to amp if the linked page has an amp version. We have amp structured like that: test.de/test/amp
Unfortunately this code in my functions.php isnt applying to links hard-coded inside of the post content. What do I have to change, so its working for every internal link:
add_filter( 'post_link', function( $url, $post ) {
static $recursing = false;
if ( $recursing ) {
return $url;
}
$recursing = true;
if ( ! function_exists( 'post_supports_amp' ) || ! post_supports_amp( $post ) ) {
return $url;
}
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
$url = amp_get_permalink( $post->ID );
}
$recursing = false;
return $url;
}, 10, 2 );
At the moment its also applying to the canonical link, which is really bad for seo. How to prevent this?
Add these functions to your theme's 'functions.php'.
/* post link filter */
add_filter( 'post_link', 'change_amp_url', 10, 2 );
function change_amp_url( $url, $postobj ) {
static $recursing = false;
if ( $recursing ) {
return $url;
}
$recursing = true;
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
if ( function_exists( 'post_supports_amp' ) && post_supports_amp( $postobj ) ) {
$url = amp_get_permalink( $postobj->ID );
}
}
$recursing = false;
return $url;
}
/* content link filter */
add_filter( 'the_content', 'change_amp_url_content' );
function change_amp_url_content($content)
{
$dom = new DOMDocument();
$dom->loadHTML($content);
$tags = $dom->getElementsByTagName('a');
foreach ($tags as $tag) {
$link = $tag->getAttribute('href'); // original url
$extralink = '';
if(stristr($link,'#')) {
$pagelinktemp = explode("#",$link);
$pagelink = $pagelinktemp[0];
$extralink = '#'.$pagelinktemp[1];
} else {
$pagelink = $link;
}
if($pagelink!="") {
$postid = url_to_postid($pagelink);
$postobj = get_post($postid); // getting appropriate post object
if($postobj) {
$newlink = change_amp_url( $pagelink, $postobj ); //new url
}
else {
$newlink = $link;
}
}
else {
$newlink = $link;
}
if($link != $newlink) // change if only links are different
{
$content = str_replace($link, $newlink.$extralink, $content);
}
}
return $content;
}
/* override canonical link */
add_filter( 'wpseo_canonical', 'amp_override_canonical' );
function amp_override_canonical($url) {
if ( substr($url,-4)=="/amp" ) {
$url = substr($url,0,-4);
}
return $url;
}
The first function will provide the AMP URL if exists.
The second one will loop through each URL in the content and change to AMP URL if valid.
The last one will rewrite the canonical URL that displayed via Yoast SEO plugin.
If you want to replace hardcoded links inside of your post content I would suggest you use the "the_content" filter for wordpress.
https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content
add_filter( 'the_content', 'filter_function_name' )
From this you should be able to regular expression match the link and append /amp to it.
Pseudo code example:
function my_the_content_filter($content)
{
if (function_exists('is_amp_endpoint') && is_amp_endpoint()) {
$patterns = array(
//patterns
);
$replacements = array(
//replacements
);
$content = preg_replace($patterns, $replacements, $content);
}
return $content;
}
add_filter('the_content', 'my_the_content_filter');
I have tested the code submitted by Outsource WordPress, and in general it works fine but the 'amp_override_canonical function overwrites all the urls of the page removing the /amp.
I have made some changes to this piece of code but they do not work as I expect. It seems that the 'wpseo_canonical' function is being invoked in a different context.
add_filter( 'wpseo_canonical', 'amp_override_canonical' );
function amp_override_canonical($url) {
if ( substr($url,-4)=="/amp" ) {
$url = substr($url,0,-4);
}
return $url;
}
I have a WordPress Child Theme and I use a php file as the template for a particular page.
I am trying to implement an API for a plugin called GeoIP Detection. Please see the PHP file I am using on my site below. The API I am trying to apply is "Redirect depending on country" located here
When I load the script, I am supposed to be redirected to https://www.google.com.sg However, it does not do so.
Thank you.
My PHP
<?php /* Template Name: GeoIPDetectionv3 */
add_action('template_redirect', 'geoip_redirect', 5);
function geoip_redirect(){
if (is_admin())
return;
// This condition prevents a redirect loop:
// Redirect only if the home page is called. Change this condition to the specific page or URL you need.
if (!is_page(90))
return;
if (!function_exists('geoip_detect2_get_info_from_current_ip'))
return;
$userInfo = geoip_detect2_get_info_from_current_ip();
$countryCode = $userInfo->country->isoCode;
switch ($countryCode) {
case 'DE':
$url = '/germany';
break;
case 'US':
$url = '/usa';
break;
case 'SG':
$url = 'https://www.google.com.sg';
break;
default:
$url = 'https://www.google.com.sg';
}
if ($url) {
wp_redirect(get_current_blog_id(null, $url));
exit;
}
}
Use a single PHP tag, and make sure the last portion of your code is in fact inside a PHP tag. Currently it is not, so it's parsed as plain text.
UPDATE: I've cleaned this up a bit for you and updated the code to reflect your revised question; i.e., following our comments below.
<?php /* Template Name: GeoIPDetectionv3 */
add_action('template_redirect', 'geoip_redirect', 5);
function geoip_redirect(){
if ( is_admin() ) {
return; // Not applicable.
}
if ( 123 !== get_current_blog_id() ) {
return; // Not on blog ID 123.
}
if ( ! is_page( 90 ) ) {
return; // Not a specific page ID on this blog.
}
if ( ! function_exists( 'geoip_detect2_get_info_from_current_ip' ) ) {
return;
}
$userInfo = geoip_detect2_get_info_from_current_ip();
$countryCode = $userInfo->country->isoCode;
switch ($countryCode) {
case 'DE':
$redirect_to = '/germany';
break;
case 'US':
$redirect_to = '/usa';
break;
case 'SG':
$redirect_to = 'https://www.google.com.sg';
break;
default:
$redirect_to = 'https://www.google.com.sg';
}
if ( ! empty( $redirect_to ) ) {
if ( stripos( $redirect_to, 'http' ) === 0 ) {
wp_redirect( $redirect_to ); // Full URL.
} else {
wp_redirect( home_url( $redirect_to ) ); // Local /path.
}
exit;
}
}
i am new to wordpress and trying to modify theme. but i am not able to track form action.
<form action="<?php echo appthemes_get_registration_url( 'login_post' ); ?>" method="post" class="login-form register-form custom" name="registerform" id="login-form">
where these action takes ? how data is stored ?
this is the function.php where i get following function code .
function appthemes_get_registration_url( $context = 'display' ) {
if ( current_theme_supports( 'app-login' ) && ( $page_id = APP_Registration::get_id() ) ) {
$url = get_permalink( $page_id );
} else {
$url = site_url( 'wp-login.php?action=register' );
}
if ( ! empty( $_REQUEST['redirect_to'] ) ) {
$url = add_query_arg( 'redirect_to', urlencode( $_REQUEST['redirect_to'] ), $url );
}
return esc_url( $url, null, $context );
}
can anyone help me with this issue?
i am stuck here.
According to the function being used
$url = get_permalink( $page_id );
The above code will get the link of the current custom login page which the theme uses.
Or else it will go to the default WordPress register page
$url = site_url( 'wp-login.php?action=register' );
There is a redirect field in the theme after the registration is over, which makes the user to go to the required page. If it is empty, then it can be skipped or else it is returned to the redirect URL specified.
if ( ! empty( $_REQUEST['redirect_to'] ) ) {
$url = add_query_arg( 'redirect_to', urlencode( $_REQUEST['redirect_to'] ), $url );
}
The data of your registration is stored in a table called users which you can access through PHPmyAdmin