By default, wordpress creates cookie for logged in users which looks like this:
Cookie Name: wordpress_logged_in_a32e4aa16e20e5346cda1
I checked wordpress core file(wp-includes/default-constants.php) from where this cookie is being created. And how I saw the cookiehash after wordpress_logged_in_ is your site url done with md5().
if ( !defined( 'COOKIEHASH' ) ) {
$siteurl = get_site_option( 'siteurl' );
if ( $siteurl )
define( 'COOKIEHASH', md5( $siteurl ) );
else
define( 'COOKIEHASH', '' );
}
if ( !defined('LOGGED_IN_COOKIE') )
define('LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH);
I need to check whether that cookie exists or has value like below:
if(isset($_COOKIE['wordpress_logged_in_a32e4aa16e20e5346cda1']) && !empty($_COOKIE['wordpress_logged_in_a32e4aa16e20e5346cda1'])){
//do something
}
But now I'm working on test website and the site url is different and once I go live, site url will be changed and cookiehash also will be changed. And I don't want to have issues after going live or after going live copy and paste new hash in my functions.php file.
Is there some dynamic way to check this cookie's existence?
You can get the site URL variable using Wordpress function.
get_site_url();
Example
<?php echo get_site_url(); ?>
//Results in the full site URL being displayed:
http://www.example.com
After getting Site URL. Calculate its MD5 in PHP. Note that to use this function outside wordpress template files, You need include Worpress wp-load.php in your php code with its path.
<?php include '../../../wp-load.php'; ?>
Once MD5 is received you can concatenate string and use in your check. Let me know in comments if you have confusion.
EDIT:
$siteurl = get_site_option( 'siteurl' );
if ( $siteurl ){
$hashedSiteUrl = md5( $siteurl );
$finalUserCookieName = 'wordpress_logged_in_'.$hashedSiteUrl;
}
if(isset($_COOKIE[$finalUserCookieName]) && !empty($_COOKIE[$finalUserCookieName])){
//some action
}
Reference: https://developer.wordpress.org/reference/functions/get_site_url/
Related
The profile-update URLs for User Profiles are language specific: .../nl/profile.php and .../en/profile.php. When users click "Update Profile" I can redirect them to any URL. But now I want to test the current URL to see if there's /nl/ in there, so I can give them a redirect to their own language. I use the code below but the result of the 'if statement' is always false. I can see that: when I enter another url there, it picks up that one. So the code seems to work, just the test fails. Any ideas what I'm doing wrong?
add_action( 'profile_update', 'custom_profile_redirect', 12 );
function custom_profile_redirect() {
if(strpos("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}", '/nl/') === false ) {
wp_redirect( trailingslashit( home_url() . '/en' ) );
} else {
wp_redirect( trailingslashit( home_url() . '/nl' ) );
}
exit;
}
[edit:] Variables I managed to retrieve are all set to 'en' after the profile update, even the plugin's global variable. I now worked around it by adding a LanguagePreference dropdown in the sign up form. In the After-Update-Redirect, I read the usermeta and redirect to their own preference.
There must be better ways to achieve this...
I want to get the permalinks of all published pages and export it to an excel file.
What is the best solution?
Should I go to wp-admin panel and copy-paste the permalinks from the on Page editor?
Can I get the export data using a mysql query?
It is possible but very difficult to do via a SQL query, because WordPress allows you to change your Permalink structure - so the SQL query would need to regard all permalink options to build the correct permalink when the query is executed.
And I guess you are looking for a way that does not require you to copy paste links from the admin page ;-)
By far the best and easiest thing to do is write a small script that runs the export for you within WordPress and uses the functions get_pages and get_permalink:
// Get a list of all published pages from WordPress.
$pages = get_pages( 'post_status=publish' );
// Loop through all pages and fetch the permalink for each page.
foreach ( $pages as $page ) { //fixed this too
$permalink = get_permalink( $page->ID );
// Do something with the permalink now...
}
Note: This code will only run inside WordPress, i.e. as as Plugin or inside a Theme. Also how to do the excel export is beyond the scope of my answer...
Personally I'd create a WordPress plugin (there are many guides out there on how this works, like this one).
In the plugin you could simply check for a URL param, and if this param is present then export the data. Additionally I would check if the user that requests the export has admin permissions before exporting the data.
A bit like this:
/**
* The WordPress plugin header...
*/
$allowed = false;
$requested = false;
// Check if the current user has admin capabilies.
if ( current_user_can( 'manage_options' ) ) { $allowed = true; }
// Check if the user requested the export.
// i.e. by calling URL http://yoursite.com?export_permalinks=1
if ( 1 == $_GET['export_permalinks'] ) { $requested = true; }
if ( $requested && $allowed ) {
// 1. Get a list of all published pages from WordPress.
$pages = get_pages( 'post_status=publish' );
// 2. Build the export data.
$export = array();
foreach ( $pages as $page ) {
$permalink = get_permalink( $page->ID );
$export[] = array( $page->ID, $permalink );
}
// 3. Export the data (I just var_dump it as example).
var_dump( $export );
// We're done, so don't execute anything else.
exit;
}
Please note that this code should only explain my suggested workflow. It does not use best practices and I don't recommend to use it like this on a live site
I have a page with the the URL format:
www.site.com/events/event.php?id=1&cat_id=4
which I'd like to rewrite to something more SEO friendly, namely
www.site.com/events/name-of-event
(I don't need the category name in my URL, just for the page to create dynamic breadcrumb links).
I have the event name in my MySQL database, and I'd like to use that in the URL. I've tried to adapt the code in this answer but without success. Can anyone help?
EDIT:
RewriteRule ^events/([^/]+)$ event.php?event_name=$1 [L,QSA] this is what I initially tried (the cat_id isn't essential to the URL as the page checks and retrieves a default if none is passed).
For backward compatibility, you probably want to redirect events/event.php?id=123 to the new events/event_name url. The problem is that, as the person said in your linked answer, there is no real way to connect to the database via Apache, so you'll have to handle the redirection/translation in the file itself.
The rule itself must look something like this:
RewriteRule ^events/([^/]+)/?$ /events/event.php?event_name=$1 [L,QSA]
Then, in your event.php you'll do something like this:
#This is the top line of your file.
if( isset( $_GET['id'] ) ) {
$id = intval( $_GET['id'], 10 );
$event_name = do_database_query_NOAW( $id );
header( 'HTTP/1.1 301 Moved Permanently' );
header( 'Location: /events/' . $event_name );
exit();
}
#code that now uses (the sanitized) event name instead of the sanitized id
if( !isset( $_GET['event_name'] ) || !preg_match( '/[A-Za-z0-9-]+/', $_GET['event_name'] ) ) {
header( 'HTTP/1.1 400 Bad Request' );
exit();
}
I am trying to run a Javascript file via conditions based on the request, (A.K.A. the previous URL) that the current page was accessed from. For example, if the user was redirected to the login page, logged in, and then returned to the previous page, that would trigger the JavaScript (whereas simply visiting the page would not).
Does WordPress or PHP have a way to check the request source?
Update:
WOOOOAAAH, WE'RE HALFWAY THEEERE!
Based on user1091949's suggestion, I have gone ahead and added code to run my JavaScript file based on the presence of a cookie:
if ( !isset( $_COOKIE['mmmcookies'] ) ) {
setcookie( 'mmmcookies', 1, 5 );
}
function media_kit_script() {
$page_id = get_queried_object_id();
if ( isset( $_COOKIE['mmmcookies'] ) ) {
if ($page_id === 1947) {
wp_enqueue_script( 'media-kit-init' );
}
}
}
add_action( 'wp_enqueue_scripts', 'media_kit_script' );
The script is registered in a previous function, and everything works! Now, here's my next question: I need to implement setcookie() based on the fact that the user has come from logging in, i.e.:
if ( user_came_from_login() ) {
if ( !isset( $_COOKIE['mmmcookies'] ) ) {
setcookie( 'mmmcookies', 1, 5 );
}
And so on. How would I do this?
You could use a cookie. The start page:
if (!isset($_COOKIE['iwashere'])) {
setcookie('iwashere', 1, time()+315360000);
}
The page where Javascript is needed if the user came from the page above:
if (isset($_COOKIE['iwashere'])) {
echo '<script src="someJavascript.js"></script>';
}
Of course, you may need to change the expire time for the cookie.
That would be the referer (and it's not very reliable):
$_SERVER['HTTP_REFERER'];
Wordpress has it's own version:
wp_get_referer()
that accesses $_REQUEST['_wp_http_referer']) internally
I have a website where I sell digital downloads, and have been trying to set up PayPal express checkout for some time. I am finally getting it integrated, but there is one thing that I can't figure out.
My code says get_script_uri( 'buy.php' ) );
This means that when the payment is processed, the user will be redirected to "buy.php".
PayPal_Digital_Goods_Configuration::return_url( get_script_uri( 'buy.php' ) );
However, my page that includes this code (paypalbuy.php) is in a directory called "dl/". When the payment is processed, and the user is redirected to 'buy.php', the user is redirected to 'dl/buy.php' because of the path.
How can I fix this? How can I set 'get_script_uri( 'http://google.com' ) );' and have the user redirected to a URL, instead of the file within the path.
EDIT: HERE IS my get_script_uri function:
function get_script_uri( $script = 'index.php' ){
// IIS Fix
if( empty( $_SERVER['REQUEST_URI'] ) )
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
// Strip off query string
$url = preg_replace( '/\?.*$/', '', $_SERVER['REQUEST_URI'] );
//$url = 'http://'.$_SERVER['HTTP_HOST'].'/'.ltrim(dirname($url), '/').'/';
$url = 'http://'.$_SERVER['HTTP_HOST'].implode( '/', ( explode( '/', $_SERVER['REQUEST_URI'], -1 ) ) ) . '/';
return $url . $script;
}
Without looking at get_script_uri() source code I can't be sure, but from the directory structure you described, I infer that by changing get_script_uri( 'buy.php' ) to get_script_uri( '../buy.php' ) should give you the correct URL you're looking for: ../ means parent directory.