get_current_user_id() returning Zero 0 - wordpress

get_current_user_id() is returning 0 for following codes. I do tried some solution available on stack overflow but somehow not working for me. I'm expecting explanation why its returning zero and how to fix?
P.S: I'm calling get_current_user_id() from external php page and included '../wp-blog-header.php' for that.
Code:
<?php
require('../wp-blog-header.php');
get_header();
$user_ID = get_current_user_id();
echo $user_ID;
?>

You have to call wordpress proccess of user authentication. Try adding the following code before get_current_user_id();, if it doesn't solve your problem it'll at least point you the right direction:
$user_id = apply_filters( 'determine_current_user', false );
wp_set_current_user( $user_id );
Hope it helps!

This is likely a result of including wp-blog-header.php directly in your external file. From the Codex on get_current_user_id():
The user's ID, if there is a current user; otherwise 0.
I'm not sure what you're trying to do, but the correct method would be to add this logic to functions.php under the correct action hook, or by writing a custom plugin. By doing one of those two things, you will have access to the authenticated user.

if you are using ajax then may be in some browser versions we can't get id by get_current_user_id() for this we can use xhrFields in over ajax then it will work fine. if the problem with the browser version.
jQuery.ajax({
type: "POST",
xhrFields: {
withCredentials: true
},
cache: false,

Related

How to detect current page in WordPress plugin development

I'm currently developing a plugin where I will restrict certain pages to the logged-in users only. I mean the normal pages we create in Wordpress.
I found this online but it does not seem to work for me.
function check_the_current_page(){
echo $slug = basename(get_permalink());
}
add_action( "init", "check_the_current_page" );
Another option I had was to detect current page id as shown in the code below. nothing gets printed on the screen, probably I'm using the wrong hook or something, someone help me
function check_the_current_page(){
global $post;
echo "Post id: ".$post->ID;
}
add_action( "init", "check_the_current_page" );
if only I'm able to get output in one of the above scenarios, then it would be very simple, but now nothing is being printed on the screen for both scenarios
Try This Code Work For Me global $post dosent work in init
function check_the_current_page() {
global $post;
echo "Post id: " . $post->ID;
}
add_action( "wp", "check_the_current_page" );

Uncaught TypeError: Cannot read property 'secret' of null wp-embed.min.js

There is an error at my console showing Uncaught TypeError: Cannot read property 'secret' of null at a.wp.receiveEmbedMessage (wp-embed.min.js?x59911:1)
Is there a way to fix this?
Issue is with Wordpress wp-embed.js . Change following following code/
if ( ! ( data.secret || data.message || data.value ) ) {
to
if ( ! data || ! ( data.secret || data.message || data.value ) ) {
On line 32. It should solve the issue. Refrence : https://core.trac.wordpress.org/ticket/44832
The issue ticket (also linked by Webmatrix) suggests the following code for wp-embed.js (starting line 31).
if ( data && ! ( data.secret || data.message || data.value ) ) {
return;
}
But changing that won't matter, since the wp-embed.min.js file is the one actually used. - And since it's all on one line, it's a little harder to find the right place.
Search for the string d.secret|| to find the right part and then replace that condition check with if(d && !(d.secret||d.message||d.value)).
I had the same issue and doing this fixed it for me, while webmatrix's code (minified) if ( !d||!(d.secret||d.message||d.value) ) didn't work for my problem.
This suggests that in my case data is in fact being passed, it just doesn't have the value that I want. Maybe there's also a problem of sometimes no data being passed at all in which case you should still add his !data || at the very beginning of my conditional, like so: if(!d||d && !(d.secret||d.message||d.value)).
Note
However, note you shouldn't be editing core files usually - because it could vanish on the next update - in this situation though, the next update is very likely to contain the same or a better fix, so if it's overwritten it shouldn't matter.
It seems like the fix for that problem depends on your WordPress version. In 4.9.8 the problematic snippet in /wp-includes/js/wp-embed.min.js looks like this:
var d=c.data;if(d.secret||d.message||d.value)if(!/[^a-zA-Z0-9]/.test(d.secret)){...}
There is no exit condition in this case, but rather a continuation condition. The following code will be executed if the previous conditions are fulfilled. Thus you need to check if the conditions are met, instead of being not met.
This worked for me:
var d=c.data;if(d&&(d.secret||d.message||d.value))...
It checks first if d is valid (not null) and then goes on to check if any of the following conditions are met.
Make sure to reload the page without the cache after uploading the fix. Ctrl+F5 for Chrome and Firefox on Windows or Command+Shift+R for Chrome and Firefox on Mac.
Modifying directly the wp-embed.min.js and it works perfectly and the console error dissapears.
Particulary, in the minified code I change this piece of code
> if(d.secret||d.message||d.value)
for this piece of code
> if(!d||!(d.secret||d.message||d.value))return;
(be carefull, the first one hasn’t got semicolon and the second one has got semicolon)
However, I do not recommend changing the WP core code in any way.
Disable Embeds in WordPress With Code
You can add the following to your WordPress theme’s functions.php file.
function disable_embeds_code_init() {
// Remove the REST API endpoint.
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
// Turn off oEmbed auto discovery.
add_filter( 'embed_oembed_discover', '__return_false' );
// Don't filter oEmbed results.
remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
// Remove oEmbed discovery links.
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
// Remove oEmbed-specific JavaScript from the front-end and back-end.
remove_action( 'wp_head', 'wp_oembed_add_host_js' );
add_filter( 'tiny_mce_plugins', 'disable_embeds_tiny_mce_plugin' );
// Remove all embeds rewrite rules.
add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
// Remove filter of the oEmbed result before any HTTP requests are made.
remove_filter( 'pre_oembed_result', 'wp_filter_pre_oembed_result', 10 );
}
add_action( 'init', 'disable_embeds_code_init', 9999 );
function disable_embeds_tiny_mce_plugin($plugins) {
return array_diff($plugins, array('wpembed'));
}
function disable_embeds_rewrites($rules) {
foreach($rules as $rule => $rewrite) {
if(false !== strpos($rewrite, 'embed=true')) {
unset($rules[$rule]);
}
}
return $rules;
}
Or you could also use the wp_dequeue_script function.
function my_deregister_scripts(){
wp_dequeue_script( 'wp-embed' );
}
add_action( 'wp_footer', 'my_deregister_scripts' );
Try to use this code. It's Working...
Thanks !

WooCommerce - Redirecting a User after They've Reset Their Password

I'm setting up a WooCommerce shop for a client and he has requested that the user be redirected back to the login form after the reset password form has been submitted.
Is this possible? Which function controls this?
Thanks in advance.
A much cleaner solution is to redirect using the woocommerce_customer_reset_password action:
function woocommerce_new_pass_redirect( $user ) {
wp_redirect( get_permalink(woocommerce_get_page_id('myaccount')));
exit;
}
add_action( 'woocommerce_customer_reset_password', 'woocommerce_new_pass_redirect' );
This code can be placed in functions.php.
Someone asked me about doing this and I think I'm going to talk them out of it, but here's what I came up with so that you could see the message and then be redirected in 5 seconds. Add a message/link to let them know you'll be redirecting. Plus, this will last through a WooCommerce upgrade if you add the template file to your theme
Add the form-lost-password.php template file to your theme and add the following code:
if ( $_GET[reset] = true && ( 'lost_password' == $args['form']) ) {
$my_account_url = get_site_url() . '/my-account';
echo "<script>window.setTimeout(function(){window.location.replace('$my_account_url')}, 5000)</script>";
}
If you dont want the time delay get rid of the window.setTimeout() and just use window.location.replace('$my_account_url').
I'm just facing the same question. I think the function that controls this is in the file woocommerce/includes/class-wc-form-handler.php. I changed the following line:
wp_redirect( add_query_arg( 'reset', 'true', remove_query_arg( array( 'key', 'login' ) ) ) );
with
wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
With that change, you get redirected to the my-account page, where the customer can log in, but of course there are two problems doing that:
The customer gets no message the the password recovery was successful
Doing a WooCommerce update, the file gets overwritten with the original file
Would be great, if someone could come up with a "update-secure" solution.
Best regards
Christoph

WooCommerce Registration Shortcode - Error messages problems

I am currently creating a widget to display the registration form on a WordPress website that uses WooCommerce. For now, I only have 3 basic fields which are email, password, repeat password. I'm looking forward to add more WooCommerce fields, but want to solve that problem before jumping to the next step.
I'm having some problems with the messages output (wrong password, account already exists, etc).
I searched on the web and there was no shortcode already built for WooCommerce registration, beside their registration page. So I went ahead and created a shortcode, with a template part.
function custom_register_shortcode( $atts, $content ){
global $woocommerce;
$form = load_template_part('framework/views/register-form');
return $form;
}
add_shortcode( 'register', 'custom_register_shortcode' );
This is a snippet I use to get the template part inside a variable, since the default function would "echo" the content instead of "returning" it.
function load_template_part($template_name, $part_name=null) {
ob_start();
get_template_part($template_name, $part_name);
$var = ob_get_contents();
ob_end_clean();
return $var;
}
So, the problem is, when I call woocommerce_show_messages or $woocommerce->show_messages(); from my template part, nothing is showing, or if it is, it shows at the top of the page.
I did try to put the calls inside my shortcode function:
function custom_register_shortcode( $atts, $content ){
global $woocommerce;
$woocommerce->show_messages();
$form = load_template_part('framework/views/register-form');
return $form;
}
add_shortcode( 'register', 'custom_register_shortcode' );
Doing so, the message output inside the <head> tag, which is not what I want.
I tried to do the same trick with ob_start(), ob_get_contents() and ob_clean() but nothing would show. The variable would be empty.
I also did try to hook the woocommerce_show_messages to an action as saw in the core:
add_action( 'woocommerce_before_shop_loop', 'woocommerce_show_messages', 10 );
For something like:
add_action( 'before_registration_form', 'woocommerce_show_messages');
And I added this in my template-part:
<?php do_action('before_registration_form'); ?>
But I still can't manage to get the error messages show inside the box. It would always be inserted in the <head>
I will share final solution when everything is done.
Thanks for your time,
Julien
I finally got this working by hooking a custom function to an action which is called in my header.php
I guess hooking functions inside template part does not work as intended.
In header.php, I got this:
do_action('theme_after_header');
And here's the hooked function. Works perfectly.
function theme_show_messages(){
woocommerce_show_messages();
}
add_action('theme_after_header', 'theme_show_messages');
However, I will look into 'unhooking' the original show message function since it might show twice. Need to test some more ;)
You can also just use the [woocommerce_messages] shortcode in your template where you want it displayed
Replying to a bit of an old question, but you can also try the following:
$message = apply_filters( 'woocommerce_my_account_message', '' );
if ( ! empty( $message ) ) {
wc_add_notice( $message );
}

"login" in permalink redirects to wp-login.php wp3.6

I'm trying to create a custom login page for a custom user page, but I can't get wordpress to stop redirecting the word login to wp-login.php.
Setup is pretty simple, I'm adding a rule that looks like this. account/login/?$ that yields to index.php?account=login. I also setup my rewrite tag for that custom query var. I have a couple other rules setup and they all work properly.
When I use monkey man's rewrite analyzer everything points properly, but on the front end any time I enter login into the url it redirects me to wp-login.php. It doesn't matter what segment it is entered at. so /login, /account/login, /dogs/bulldogs/login.... all redirect to wp-login.php
As far as I can tell there aren't any other rewrite rules containing login. So i'm at a loss.
As a last piece of info, i'm working in wp 3.6
Any advise or ideas would be greatly appreciated.
I'm facing the exact same problem. Google wasn't being very helpful, so I had the need to dig in. :)
Right on top of the wp-includes/template-loader.php file, you find this little snippet of code:
if ( defined('WP_USE_THEMES') && WP_USE_THEMES )
do_action('template_redirect');
If you inspect what functions are hooked to that action at that time, you'll find a reference to the wp_redirect_admin_locations function (both the hook and the function are declared on the /wp-includes/canonical.php file - line 526).
Within the wp_redirect_admin_locations function, you'll find this:
$logins = array(
home_url( 'wp-login.php', 'relative' ),
home_url( 'login', 'relative' ),
site_url( 'login', 'relative' ),
);
if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins ) ) {
wp_redirect( site_url( 'wp-login.php', 'login' ) );
exit;
}
An easy solution for the problem, would be to hook a function of yours to the *wp_redirect* filter. Something like this (within your functions.php):
add_filter('wp_redirect', 'yourprefix_filter_login_redirect', 10, 2);
function yourprefix_filter_login_redirect($location, $status)
{
$uri = trim($_SERVER['REQUEST_URI'], '/');
if ($uri === 'login') {
return false;
}
return $location;
}
So... The *wp_redirect_admin_locations* terminates the script after trying to preform the redirect, so the solution above won't work.
The only other solution I'm seeing right now is to bypass the function all together which kind of sucks. All the other redirects defined within that function, will be lost all together...
Anyway, what I've ended up using:
add_action(
'init',
function() {
remove_action('template_redirect', 'wp_redirect_admin_locations', 1000);
}
);
Building on top of Diogos great answer, you can even disable the /login redirect without losing the other redirects. I just posted this solution on WPSE: Disable "/login" redirect

Resources