I have create a custom url for my plugin in WordPress that I don't like to have any argument.
Lets say that my URL us that
http://www.mysite.ext/test/
How can I know from my code that the users in on /test/ and not in any other page from within my code ?
This is my code:
add_action('init', 'add_rewrite_rule');
function add_rewrite_rule()
{
add_rewrite_rule('test/?', 'index.php', 'top');
}
if you only want to test whether the current pages ends with /test/, can you do it in php like this:
//get host name, this returns www.mysite.ext
host = $_SERVER['HTTP_HOST'];
//get full path, this returns /test
$script = $_SERVER['SCRIPT_NAME'];
This is not test, but worth trying.
Related
I need Geo information from each users who visit my website in wordpress, in order to present correct current. After I use cloudfront, the WC_Geolocation doesn't work. I was thinking picking cloudfront-view-country header from cloudfront request to my server. The below two method I have test, but didn't get what i expected.
Add the cloudfront-view-country to Whitelist Headers. Use getallheaders() to read the request headers in the wordpress in functions.php, but didn't find the expected header cloudfront-view-country.
snippet in the functions.php
$headers = getallheaders();
foreach($headers as $key=>$val){
echo $key . ': ' . $val . '<br>'
}
I use lambda + API gateway, pass CloudFront-Viewer-Country to lambda in Body Mapping Templates
detect_countryCode": "$input.params('CloudFront-Viewer-Country')
catch the countryCode with event in lambda
exports.handler = (event, context, callback) => {
let countryCode = event.detect_countryCode;
callback(null, countryCode)
};
When I test with API in a browser, it did show the right country code. However, after I use wp_remote_get() to integrated this API in wordpress. It always shows "US" which is my server's locationi. I believe the logic is wrong in the second method. It is my server invoke the API, of course it will return the country code of my server which is in "US".
Any comments would be appreciated.
Thank you.
I've read couple of previous post here but none of them is working in my case.. Basically, my blogging site is installed in a sub-directory of main website.. Main website in plain php and sub-directory is wordpress.. I allow users to read my blogs only after logged in. So, the thing is I frequently share the blog links in facebook where lots of new users come in from the link.
Main website is installed in => example.com
wordpress sub-directory in => example.com/blog
As I'm using the custom template login page (login.php), whenever the non-logged in users comes- first they are redirected to example.com/blog/login. I'm using this function to redirect to login page:
function redirect_user() {
if ( ! is_user_logged_in() && !is_page( 'login' ) ) {
$return_url = esc_url('http://www.example.com/blog/login');
wp_redirect( $return_url );
exit;
}
}
add_action( 'template_redirect', 'redirect_user' );
It redirect fine, without problem.. Then the main task of redirecting to the referrer url, I'm using the similar code above to direct to every logged in users to the referring url irrespective or post or page.. Again in the functions.php
if(is_user_logged_in())
wp_redirect('' . $_SERVER["REQUEST_URI"]);
I thought they would work but can't seems to understand that referring url is appending the sub-directory name... For example; the above code show result as:
example.com/blog/blog/blabla-blahblah.. You see the directory name is doubling..
Anyone's advice would be highly appreciated..
Having your WordPress website in a subdirectory will have no impact on what you are trying to do. Why? Because WordPress knows where it's located at, as you set the home and site URLs either in your wp-config.php file like this:
define('WP_HOME','http://example.com/blog');
define('WP_SITEURL','http://example.com/blog');
or by setting both in the Settings > General admin page:
Therefore, all of the rewrites and URLs will be relative to these URLs.
Handling the Referer Capture
When someone comes to one of the pages on your site, you want to capture that original request and add it as a redirect_to= query arg. Then you can send them to the login page.
add_action( 'wp', 'redirect_to_login_if_unauthorized', 3 );
/**
* Redirect the user to the login, but capture the original
* referer and add to the query arg.
*
* #since 1.0.0
*
* #param WP $wp_environment Current WordPress environment instance (passed by reference).
*
* #return void
*/
function redirect_to_login_if_unauthorized( WP $wp_environment ) {
if ( is_user_logged_in() ) {
return;
}
if ( $wp_environment->request ) {
$request = home_url( add_query_arg( array(), $wp_environment->request ) );
} else {
$request = home_url();
}
$redirect = home_url() . '/wp-login.php?redirect_to=' . $request;
wp_redirect( $redirect );
die();
}
How it Works
The event wp fires in wp-includes/class-wp.php. It passes the object instance of the WordPress environment setup. Here is the code from WordPress Core:
do_action_ref_array( 'wp', array( &$this ) );
This environment object has a property that we want called request. That property has the URL request (minus the blog's home URL).
If the $wp_environment->request has a value, we'll add it to the home URL as a query arg; else, we just want the home URL. Now we have the referer.
Next, you create the redirect URL, which has the path to the login page and the redirect_to query arg.
An Example
Let's say you have a post called Why I Love WordPress and the path to that post is http://example.com/blog/why-i-love-wordpress.
The value in the $request would be:
http://example.com/blog/why-i-love-wordpress
and the redirect URL would be:
http://example.com/blog/wp-login.php?redirect_to=http://example.com/why-i-love-wordpress
Upon logging in, the user is then redirected to the original page request.
Tip - Handle Logout Too
You'll want to think about the pathing after a user logs out and then build a proper request to it too.
We have files behind authentication, and I want to do different things for post-authentication redirect if the user entered the application using a URL of a file versus a URL of an HTML resource.
I have a URL: https://subdomain.domain.com/resource/45/identifiers/567/here/11abdf51e3d7-some%20file%20name.png/download. I want to get the route name for this URL.
app/console router:debug outputs this: _route_name GET ANY subdomain.domain.{tld} /resource/{id2}/identifiers/{id2}/here/{id3}/download.
Symfony has a Routing component (http://symfony.com/doc/current/book/routing.html), and I'm trying to call match() on an instance of Symfony\Bundle\FrameworkBundle\Routing\Router as provided by Symfony IOC. I have tried with with the domain and without the domain, but they both create a MethodNotAllowed exception because the route cannot be found. How can I match this URL to a route?
Maybe a bit late but as I was facing the same problem, what I come to is something like
$request = Request::create($targetPath, Request::METHOD_GET, [], [], [], $_SERVER);
try {
$matches = $router->matchRequest($request);
} catch (\Exception $e) {
// throw a 400
}
The key part is to use $_SERVER superglobal array in order to have all things setted straight away.
According to this, Symfony uses current request's HTTP method while matching. I guess your controller serves POST request, while your download links are GET.
The route name is available in the _route_name attribute of the Request object: $request->attributes->get('_route_name').
You can do something like this ton get the route name:
public/protected/private function getRefererRoute(Request $request = null)
{
if ($request == null)
$request = $this->getRequest();
//look for the referer route
$referer = $request->headers->get('referer');
$path = substr($referer, strpos($referer, $request->getBaseUrl()));
$path = str_replace($request->getBaseUrl(), '', $lastPath);
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($path);
$route = $parameters['_route'];
return $route;
}
EDIT:
I forgot to explain what I was doing. So basicly you are getting the page url ($referer) then taking out your website's base url with str_replace and then trying to match the remaining part of the path with a know route pattern using route matcher.
EDIT2:
Obviously you need to have this inside you controller if you want to be able to use $this->get(...)
I am successfully using the 'Friendly URL' module in ASP.NET 4.5
In route config I can add a route like this:
routes.MapPageRoute("mypage", "mypage/{mypageName}", "~/mypage.aspx");
for a URL like this:
mysite.com/mypage/hello
in the page 'mypage.aspx' I can get URL segments like this:
using Microsoft.AspNet.FriendlyUrls;
// Get URL segments
IList<string> segments = Request.GetFriendlyUrlSegments();
if (segments.Count > 0)
{
// Get first segment
string url = segments[0];
}
However, I cannot get this working for root URL's. e.g. 'my site.com/ttee'
I want to get 'ttee' and pass it into a page. But 'Request.GetFriendlyUrlSegments()' returns 0 for the root.
How best can I do this?
routes.MapPageRoute("mypage", "mypage/{mypageName}", "~/mypage.aspx");
This will work only for URLs in this format:
www.example.com/mypage/changingparthere
If you want to make it
www.example.com/changablemypage
Set it to:
routes.MapPageRoute("mypage", "{mypageName}", "~/mypage.aspx");
But as you can see, it will catch literally everything. So make sure it is the last routing on Global.asax.
I have a WordPress site in two languages (Hebrew and English) and I need it to redirect according to browser language. I'm using qTranslate plugin to create the content in both languages. This plugin also has a redirection functionality but it creates a redirection only for the homepage and I need the redirection to happen for internal pages as well as the homepage.
Another developer wrote this code for me to create the redirection, but for some reason it creates a funny redirect. It happens only when switching language to Hebrew, then leaving the site and trying to enter directly to http://domain.com/en/ and it redirects you to http://domain.com/domain.com/ (Does not happen when switching to english).
I tried playing with the "header (Location: )" that creates the redirection for Hebrew, but couldn't figure out how to make it work - I tried using the full path instead of relative path, or removing the "/" between $_SERVER['SERVER_NAME'] and $_SERVER['REQUEST_URI'] but got recursive url or url with double "/" (http://domain.com// and also for internal pages http://domain.com//page).
The url structure is:
domain.com/ for Hebrew
domain.com/en/ for English
and when switching language then the parameter $lang=en or $lang=he is being added.
Hope this makes sense, and thanks a lot!
this is the code that is responsible for the redirection:
<?php
if (!isset($_COOKIE["uln"])) :
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
setcookie('uln', $lang, time()+86400*365, '/', '.domain.com'); // cookie stored for a year
$_COOKIE['uln'] = $lang;
endif;
//if lang=(value) is not empty
if(isset($_GET['lang'])) {
$lang = $_GET['lang'];
setcookie('uln', $lang, time()-1, '/', '.domain.com'); //this unsets the cookie for random language selection
//set the cookie "uln" again with the selected language.
setcookie('uln', $lang, time()+86400*365, '/', '.domain.com'); // cookie stored for a year
$_COOKIE['uln'] = $lang;
}
if(($_COOKIE["uln"]) == "en") {
$matched = strncmp("/en/", $_SERVER['REDIRECT_URL'], 3);
if ($matched !== 0) :
header('Location: /en'.$_SERVER['REQUEST_URI']);
endif;
} elseif(($_COOKIE["uln"]) == "he") {
$matched = strncmp("/en/", $_SERVER['REDIRECT_URL'], 3);
if ($matched === 0) :
header('Location: '.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);
endif;
}
?>
instead of
header('Location: '.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);
try
header("Location: http://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}");
URLs, especially those in Location headers, should include a protocol and domain name. I believe relative URLs in Location headers are a violation of the HTTP RFCs.
By omitting a protocol, you're unintentionally specifying a relative url instead of an absolute one.
Edit: REQUEST_URI is already prefixed with a / so including one in the concat is unnecessary.
You're missing an http:// somewhere, probably in the English -> Hebrew redirect code.
Change
header('Location: '.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);
to
header('Location: http://'.$_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI']);