get_current_user_id() creates blank screen - php

I need to get the current user id to lookup customer information, in order to pass it to an api call to process a payment.
I have tried:
$user = wp_get_current_user();
echo ( isset( $user->ID ) ? (int) $user->ID : 0 );
and:
$userid = get_current_user_id();
echo $userid;
But when I run the php file, the process stops at the first line and does not display anything after it. I dont get an error or nothing, just a blank screen.
I have been searching for solution for 2 weeks. All results says that these codes should work, but does not for me.
I have also added the require('to user.php') and doe not work.
I even enter this php code into Dreamweaver, and "wp_get_current_user" or "get_current_user_id" does not turn blue like other function calls do, but get_current_user() does turn blue, but this is the websites owners user not the current user.
Please help if you can, much appreciated.
Thanks
Here is my code:
<?php
echo "here";
/**
* Lookup the customer information.
*
* #since 1.0.0
*
* #return void
*/
echo "is";
function lookup_customer_information() {
$current_user = wp_get_current_user();
if ( ! is_object( $current_user ) || ! isset( $current_user->ID ) ) {
echo $current_user;
return;
}
echo "the";
echo "code";
// do your business logic here.
}
?>
<?php $userinfo = lookup_customer_information();
echo $userinfo;
?>

From what you describe, it sounds like WordPress Core has not loaded the wp-includes/user.php file yet or the current user has not been setup yet.
WordPress, like all apps, load in a particular order. What may be causing the issue for you is the current user has not been setup and/or the user files (in Core) have not loaded yet.
Let's See if Function is Available
Let's discover if the function wp_get_current_user is ready to be used. You can do any of these:
Check the PHP error logs
Check your settings to display the errors
Put code in to check for it
Let's use the third option to show you if it's available or not. Put this code snippet in above your if conditional you show in your question:
if ( ! function_exists( 'wp_get_current_user' ) ) {
die('The file with wp_get_current_user() has not loaded yet into memory.');
}
The code will use the PHP construct function_exists to check if wp_get_current_user has been loaded into memory. If yes, you will not get the message, as it's ready. Else, the website will stop loading and you'll get the above message displayed on the screen.
No, It's Not Available
If the website renders the above message on the screen, then you know it's not loaded into memory yet. That means you are trying to use it before WordPress Core has loaded it.
How to Fix
Delay. You want to wait until WordPress has setup the user. Typically, you can register to the init event or later. For example, you can do this:
add_action( 'init', 'lookup_customer_information' );
/**
* Lookup the customer information.
*
* #since 1.0.0
*
* #return void
*/
function lookup_customer_information() {
$current_user = wp_get_current_user();
if ( ! is_object( $current_user ) || ! isset( $current_user->ID ) ) {
// you might want to post a message
return;
}
// do your business logic here.
}
Yes, It Is Available
When running the function_exists() snippet above, you did not get the message. Hum, something else is up then.
Now, it's time to dig into your PHP error logs to see what is going on. You can post them to help us help you.

Related

Multiple PayPal accounts linked to ONE installation of Woocommerce

My issue: The client has 12 locations, each location is a different corporation hence a different PayPal account per business. By default woocommerce only supports one email to be entered to process the payment. The goal is to use one installation of wordpress / woocommerce then direct the user to the PayPal account associated with the location they have selected upon checkout.
My Theory / Attempt: originally I thought of implementing this feature by setting up a variation so the user can select a location which will then pass a parameter to the URL. The parameter would later be used within the PHP to overwrite the default email.
My Problem: I am having trouble with overwriting the default email that is entered within the admin settings, I cant seem to locate this email in the database. I am assuming the file pertaining this modification is located at: wp-content/plugins/woocommerce/includes/gateways/paypal but would prefer doing this the wordpress way vs editing core files, for obvious reasons. After doing some research I have found the following action shown below, but this is for the proceed to checkout button, I am looking to interact with the proceed to PayPal button. I am fluent in PHP but not the best with WordPress development. I would think this is a popular issue since majority of franchises would deal with such a scenario, but I am unpleasantly surprised on the amount of information regarding this topic. If someone could point me in the right direction of conquering this task it would be greatly appreciated!
remove_action('woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
add_action('woocommerce_proceed_to_checkout', 'change_url_to_checkout', 20);
function change_url_to_checkout(){
$extra_url = 'put_your_extra_page_url_here';
?>
<?php _e( 'Proceed to Checkout', 'woocommerce' ); ?>
<?php
}
I can see two functions to be written here.
1. To alter the order data when an order is created. This is where we save the email needed.
add_action( 'woocommerce_checkout_update_order_meta', 'woocommerce_checkout_update_order_meta' );
function woocommerce_checkout_update_order_meta( $order_id ) {
$email = 'paypal#location1.com';
// do something here as to use the right email.
// you have $order_id.
// can be used as:
// $order = wc_get_order( $order_id );
// $order->get_billing_address_1() to get the address to check order address.
// or use $_POST['location'] if ever you posted some data.
update_post_meta( $order_id, '_alternative_paypal_email', $email );
}
2. Then use woocommerce_paypal_args to alter the args that is being passed to paypal.
add_filter( 'woocommerce_paypal_args', 'woocommerce_paypal_args', 10, 2 );
function woocommerce_paypal_args( $paypal_args, $order ) {
$email = get_post_meta( $order->get_id(), '_alternative_paypal_email', true );
if ( !empty( $email ) ) {
$paypal_args['business'] = $email;
}
return $paypal_args;
}
To summarize, this is just an example. But these two hooks is enough to get what you need.

I have a function that only allows users to see their own files, I want to disable this for admin/editors but struggling to get it to work

I'm using the following code to let users only access their own media files, which works great;
add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );
function show_current_user_attachments( $query = array() ) {
$user_id = get_current_user_id();
if( $user_id ) {
$query['author'] = $user_id;
}
return $query;
}
The trouble is, I want to do this for those with a user role lower than editor (So editors/admins only can see all the media files).
I have tried wrapping my function in this code but it didn't seem to work as intended, it just hangs whilst trying to load the media files (for any user), here's a screenshot of what it looks like.
Does anyone have any suggestions for solving this issue?
Thanks, Harry.

Don't allow register user url if it exists in wordpress

I'm trying to set up registration on WordPress that doesn't allow user's website to register more times. Simply said - I don't want one user to register many times with the same website. This works with emails and username. If the email is already in use won't allow registration. The same thing but for the users urls. Do you have any suggestion how to set up? Thanks!
I have tried to create a function that checks for url and if it finds it will create an error. But I'm not sure if there are other instances that prevents my set up because it doesn't work. Also I'm using wp-members plugin for registration. The code I was trying to edit was in wp-includes/users.php
function user_url_exists( $user_url ) {
if ( $user_url = get_user_by('url', $user_url) ) {
return $user_url->ID;
} else {
return null;
}}
if ( !$update && ! defined( 'WP_IMPORTING' ) && user_url_exists($user_url) ) return new WP_Error('existing_user_url', __('This website address is already registered.') );
You can try WangGuard plugin. :)
I'm sorry but this must be asked in WP Members forum. Thought you were developing a custom code... :(
http://butlerblog.com/wp-members/
Best!
R

Wordpress Future Page Issue (Not Showing)

I've been asked to fix a problem on a wordpress site. The problem is caused by the fact posts should of been used instead of pages. However the site is up and running and quickest option would be to fix the problem using a hack of sorts.
The site has an events section, each event is a page (this is the issue, should really be a post). In order to have upcoming and past events the post date is used, therefore upcoming events has a post status of 'future'.
There's are list page of events which shows them fine by using the correct query_post(). Although the problem arises when you click through to actual event (which is a future page). If your logged in as an Admin then the page shows but if your not logged in you get a 404 page.
Now if they where posts then the "The Future is Now!" plugin would solve this problem. I have a feeling the only way round the problem is to rewrite part of core Wordpress files.
Any advice would be great, I have a lot of experience with Wordpress so even if you can point me in the right direction.
Cheers,
Jason
[Update]
Thanks maiorano84 for your detailed response. In the long run I intend to move them to posts but in the meantime they've requested we fix it asap without changing any urls (today they sent out a mass email with a list of events without checking any links)
Your solution of including post_status future doesn't work in this case as wordpress doesn't get to the stage of loading the template. Something in wordpress core stops it from getting that far. Ideally if they was a hook I could use to override this behavior in the meantime that would be excellent but if it comes to it I will temporarily edit the core files.
[Update 2]
I now know the two functions that need editing or use a hook that relates to them.
First of we is_404() which needs changed to not add future pages as 404
Second we have is_page() need to return true if a page is future
[Update 3]
I've found how to do this in the core. If you go to wp-includes/query.php line 2682. Copy this in instead of the old function it works correct. If you have a better way please let me know. Thanks.
/** Future Pages **/
// Check post status to determine if post should be displayed.
if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
$status = get_post_status($this->posts[0]);
$post_status_obj = get_post_status_object($status);;
if ( !$post_status_obj->public ) {
if ( $post_status_obj->protected ) {
$this->is_preview = true;
print_r($status);
if ( 'draft' != $status ) {
$this->posts[0]->post_date = current_time('mysql');
} else {
$this->posts = array();
}
} elseif ( $post_status_obj->private ) {
if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
$this->posts = array();
} else {
$this->posts = array();
}
}
/** END **/
You can actually add a post_status parameter of 'future' to your page queries. You REALLY shouldn't be modifying your core files in order to do what you want. So on your page.php and archive.php templates (or other relevant templates that's controlling your Event display), you can do something like this:
<?php
$params = array('posts_per_page'=>-1, 'post_status'=>'publish,future');
$query = new WP_Query($params);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
?>
<!-- YOUR PAGE HTML HERE -->
<?php
endwhile;endif;
wp_reset_postdata();
?>
This is an oversimplification, but using the correct queries in the corresponding files will allow you to display your pages however you like.
More information here: http://codex.wordpress.org/Class_Reference/WP_Query
Another thing worth considering, and I realize that this wasn't a part of your question, but may very well solve your issue:
Why not create a subdomain on your client's server where you can work on fixing everything without interrupting the user experience? You can easily either import the existing database into your development environment, and make all the changes you need without affecting the live version.
Food for thought. My advice would be to nip this in the bud, and convert the pages over to posts as soon as possible, otherwise the website will turn into a giant mess very quickly, but that's your call.
Hope this helps.
UPDATE:
I would still advise against altering the core files, but if it's a last resort until everything gets fixed, then have at it. Here's is a "WP Friendly" solution I think might help:
add_action('wp','future_redirect', 0);
function future_redirect($WP_Object)
{
$page = is_page() ? get_page(get_the_ID()) : false;
if($page && $page->post_status == 'future')
{
wp_redirect(/*YOUR REDIRECT URL*/);
exit();
}
return $WP_Object;
}

PHP script for Wordpress for Comment Approval

I want to write PHP script (standalone) for comment approval.
Objective:
I use Aksimet for comment filtering. After Akismet's filtering, few comments get passed and come to my email for approval. I will get comment ID from there and pass it to the script in get parameter (manually).
This way I do not need to login to WP every time. The script will just approve comment so there is not much risk or harm. If script works then It will take less time and I can approve comment any time even from office.
I tried setting the moderation bit in MySQL directly to see if it works or not! The answer is yes and no. It approves the comment but it does not refresh the post. So, my cache show post without new comment. I use Super cache plugin.
The challenge is to write script OUTSIDE of WP environment. So, that I can access the script without Admin login.
Please suggest trick for this and how to start for this.
I spent a little time and got this working. The key is that you can use the WP API in your script by including wp-load.php.
I have tested this below and it works in my Wordpress. It uses GET parameters 'commentid' and 'status'. I leave it to you to extend, test for error conditions, provide appropriate security mechanisms, etc.
<?php
include('wp-load.php');
echo 'Running comment approval...<br>';
$wp_error = false;
if(isset($_GET['commentid']) && isset($_GET['status']) )
{
$comment_id = $_GET['commentid'];
$comment_status_to_set = $_GET['status'];
$current_status = wp_get_comment_status( $comment_id );
echo 'Current comment status is ' . $current_status .'<br>';
echo 'Setting status to ' . $comment_status_to_set . '<br>';
$res = wp_set_comment_status($comment_id, $comment_status_to_set, $wp_error);
$new_current_status = wp_get_comment_status( $comment_id );
echo 'Now status is ' . $new_current_status . '<br>';
}
else
{
echo 'No comment parameters passed in url';
}
?>
And here is the usage for wp_set_comment_status, from the source code:
#param int $comment_id Comment ID.
#param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
#param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
#return bool False on failure or deletion and true on success.
Also, so those who are curious know how I went about solving this... basically I checked the /wp-includes/ directory of WP to see if there were any comment related files. There is a file called comment.php in there, which has most, if not all, of the main comment manipulation functions that the wordpress API uses.
#param int $comment_id Comment ID.
#param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
#param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
#return bool False on failure or deletion and true on success.

Categories