So I am trying to run a simple if statement inside the wp-functions.php file and am using current_user_can. However I get PHP errors like: "Fatal error: Call to undefined function current_user_can() in..."
If anyone could take a look at my code, that would be much appreciated.
The code I am using is here:
global $current_user_can;
if ( current_user_can( 'manage_options' ) ) {
/* Admin User */
} else {
/* Member */
echo "<p>something</p>";
}
This usually happens because pluggable.php is not loaded by some reason. Try to add this before your function;
if(!function_exists('wp_get_current_user')) { include(ABSPATH . "wp-includes/pluggable.php"); }
It just checks if pluggable is loaded, and if not, it includes it.
if you want to check directly the role of the member, you can use this code:
global $current_user;
get_currentuserinfo();
if( !in_array( 'administrator', $current_user->roles ) ) {
//Do something
} else {
//Do something else
}
if you are creating a plugin, you must have to include like
if(!function_exists('wp_get_current_user')) { include(ABSPATH . "wp-includes/pluggable.php"); }// no need to add for theme functions
global $current_user_can;
if ( ! current_user_can( 'manage_options' ) ) {
// your stuff here
}
Related
I want to redirect the user to cart page after he logs in if the cart is not empty. I am trying this:
function woocommerce_custom_redirects() {
if(!WC()->cart->is_empty() )
wp_redirect( "https://edkasa.com/checkout" );
}
add_action('wp_login', 'woocommerce_custom_redirects');
But this is not working, I am using buddypress plugin, any idea where am I going wrong.
With the wp_redirect() Function, it is suggested to follow that up with an explicit call to exit. For further Information on that, see Documentation.
You may thus try adding that to your Code... Something like:
function woocommerce_custom_redirects() {
ob_start(); // COULD BE A GOOD IDEA
if ( WC()->cart->get_cart_contents_count() !== 0 || !WC()->cart->is_empty() ) {
wp_redirect( "https://edkasa.com/checkout" );
exit; // VERY VITAL HERE TO EXPLICITLY CALL exit...
}
}
add_action('wp_login', 'woocommerce_custom_redirects');
I am looking for and can not find anywhere as I can redirect the empty woocommerce cart to the homepage. I only find redirects that go to the store.
This is what I find, but I do not need to redirect to the home:
add_action("template_redirect", 'redirection_function');
function redirection_function(){
global $woocommerce;
if( is_cart() && WC()->cart->cart_contents_count == 0){
wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
}
}
Thanks
just removed static link of previous answer.
function woocommerce_custom_redirects() {
ob_start(); // COULD BE A GOOD IDEA
if ( WC()->cart->get_cart_contents_count() !== 0 || !WC()->cart->is_empty() ) {
global $woocommerce;
$checkout_url = $woocommerce->cart->get_checkout_url();
wp_redirect($checkout_url);
exit; // VERY VITAL HERE TO EXPLICITLY CALL exit...
}
}
add_action('wp_login', 'woocommerce_custom_redirects');
This question already has answers here:
The plugin generated X characters of unexpected output during activation (WordPress)
(25 answers)
Closed 4 years ago.
I want to create a wordpress plugin by just following the example listed here based on a class OOP architecture with an external setup object, and adapting the source code on my own way like this:
main plugin file:
<?php
/*
Plugin Name: My Plugin
Description: My Plugin
Version: 1.0
Author: drwhite
Author URL: drwhite-site
Plugin URL: drwhite-site/video-ad-overlay
*/
register_activation_hook(__FILE__, array( 'VAO_Setup_File_Inc', 'on_activation'));
register_deactivation_hook(__FILE__, array( 'VAO_Setup_File_Inc', 'on_deactivation'));
register_uninstall_hook(__FILE__, array( 'VAO_Setup_File_Inc', 'on_uninstall'));
add_action('plugins_loaded', array( 'VAO_Setup_File', 'init'));
class VAO_Setup_File{
protected static $instance;
public static function init()
{
is_null( self::$instance ) AND self::$instance = new self;
return self::$instance;
}
public function __construct()
{
add_action( current_filter(), array( $this, 'load_files' ));
}
public function load_files()
{
foreach ( glob( plugin_dir_path( __FILE__ ).'includes/*.php' ) as $file ){
include_once $file;
}
}
}
In my plugin root directory i have created a subdirectory called includes within i put the setup file to be loaded on plugin load called setup.class.php:
<?php
class VAO_Setup_File_Inc
{
public static function on_activation()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
$plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
check_admin_referer( "activate-plugin_{$plugin}" );
}
public static function on_deactivation()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
$plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
check_admin_referer( "deactivate-plugin_{$plugin}" );
}
public static function on_uninstall()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
check_admin_referer( 'bulk-plugins' );
// Important: Check if the file is the one
// that was registered during the uninstall hook.
if ( __FILE__ != WP_UNINSTALL_PLUGIN )
return;
}
}
When i activate the plugin i got an error like the following:
I have read several questions posted by other users here and this may be duplicated question, but any of suggested answer worked for me including:
Remove space from start of tags and even remove the php end tag: nothing changed
in wp_config.php file i set wp_DEBUG to true , but it doesn't show errors
I have converted the file to UTF8 (without BOM) nothing changed
Have you put the eye in the issue ?
You are getting this error because your plugin is generating a PHP error that is being outputted to the page and causing the headers sent error you see... The problem with your code is that your function
public function load_files()
{
foreach ( glob( plugin_dir_path( __FILE__ ).'includes/*.php' ) as $file ){
include_once $file;
}
}
is not being called in time, so
register_activation_hook(__FILE__, array( 'VAO_Setup_File_Inc', 'on_activation'));
is looking for a function that doesn't exist, inside a class that doesn't exist. Move your
foreach ( glob( plugin_dir_path( __FILE__ ).'includes/*.php' ) as $file ){
include_once $file;
}
outside the class altogether, and it'll load just fine. It may require you to rethink your use of
add_action('plugins_loaded', array( 'VAO_Setup_File', 'init'));
and the way your plugin is being created, but it's a step in the right direction. If you copy and paste the code from the link you got this code from, his code displays the same problem...
How do I check if a user is admin before running a function in a Wordpress plugin. Something that seems like it should be trivial is a pain.
I've looked at dozens of posts online and can't find one thing that works. I tried the following for example (among half a dozen other things) which is a function in a plugin :
global $current_user;
if ( $current_user->role[0]=='administrator' ) {
function remove_post_metaboxes() {
remove_meta_box( 'formatdiv','album','normal' );
}
add_action('admin_menu','remove_post_metaboxes');
}
<?php if (current_user_can( 'manage_options' )) {
// do stuff
} ?>
$current_user = wp_get_current_user();
// print_r($current_user);
if ($current_user->has_cap('administrator')) {
// do something
echo 'is an admin';
}
So I was doing this wrong, the answer supplied by ReLeaf is partially correct but nobody pointed out that instead of trying to wrap the function like the example I gave in the original question and is why i was getting a blank admin screen :
global $current_user;
if ( $current_user->role[0]=='administrator' ) {
function remove_post_metaboxes() {
remove_meta_box( 'formatdiv','album','normal' );
}
add_action('admin_menu','remove_post_metaboxes');
}
I should have had the conditional inside the function instead :
function remove_post_metaboxes() {
global $current_user;
if ( $current_user->role[0]=='administrator' ) {
remove_meta_box( 'formatdiv','album','normal' );
}
}
add_action('admin_menu','remove_post_metaboxes');
So that's how it's done, thanks me for pointing it out to me ;)
I am developing a plugin for wordpress, I want to find if current user is administrator or not, unfortunately I could not use the current_user_can() as it gives me error, so am using the global $current_user. But I could not get inside the if part even for admin user.. How to fix this?
global $current_user;
if ($current_user->role[0]=='administrator'){
function hide_post_page_options() {
//global $post;
// Set the display css property to none for add category and add tag functions
$hide_post_options = "<style type=\"text/css\"> .jaxtag { display: none; } #category-adder { display: none; } </style>";
print($hide_post_options);
}
add_action( 'admin_head', 'hide_post_page_options' );
}
Try something like the following:
if ( current_user_can( 'manage_options' ) ) {
/* A user with admin privileges */
} else {
/* A user without admin privileges */
}
Read more about the current_user_can function here.
Get the user and check if it has the role adminstrator, like so:
function is_site_admin(){
return in_array('administrator', wp_get_current_user()->roles);
}
if (is_site_admin()) {
echo 'Woot Woot';
} else {
echo 'So sad, I have no rights';
}
This works for me:
global $current_user;
if( !empty($current_user->roles) ){
foreach ($current_user->roles as $key => $value) {
if( $value == 'administrator' ){
Do Something
}
}
}
If it's not a multi-site set-up, you can use this to detect an administrator. If it's multi-site, this will only return true for a super admin.
$user_ID = get_current_user_id();
if($user_ID && is_super_admin( $user_id )) {
Do Something
}
I know it is an old question but I would like to make this page more useful by addressing the actual issue. The actual issue here is that OP hasn't been able to use current_user_can( 'manage_options' ) in his plugin. Using the function raises the usual undefined function... PHP error. This happens because the plugin gets initialized before WP core completes loading. Fix is very simple. Loading the plugin at appropriate time is the key.
Assuming the admin plugin code resides inside a class MyPlugin, the class initialization should be hooked to init. Following is one way of doing it.
/**
* Plugin Class
*/
class MyPlugin{
public function __construct(){
/* all hooks and initialization stuff here */
/* only hook if user has appropriate permissions */
if(current_user_can('manage_options')){
add_action( 'admin_head', array($this, 'hide_post_page_options'));
}
}
function hide_post_page_options() {
// Set the display css property to none for add category and add tag functions
$hide_post_options = "
<style type=\"text/css\">
.jaxtag { display: none; }
#category-adder { display: none; }
</style>";
print($hide_post_options);
}
}
add_action('admin_init', function(){
$myplugin = new MyPlugin();
});
This is a way of making sure that wordpress core is available to the plugin function.
You can find admin_init documentation here.
P.S. You should look into using PHP HEREDOC. It is a very simple way of writing multi-line strings. Your style block can be re-written as follows
$hide_post_options = <<<HTML
<style type="text/css">
.jaxtag { display: none; }
#category-adder { display: none; }
</style>
HTML;
I hope it helps somebody.
Thanks.
Too late for an answer for this question, but I think it might be useful anyway if someone ends up here like me.
I needed a quick solution to this problem - check if the current user is admin or not.
From the WP codex I got a simple solution which is to use..
if(is_super_admin($user_id)) {
// do stuff for the admin user...
}
According to WP-Codex this function returns True if the currently logged in user is network (super) admin. This function returns True even if the network mode is disabled but the current user is admin.
<?php
if( current_user_can( 'administrator' ) ){} // only if administrator
if( current_user_can( 'editor' ) ){} // only if editor
if( current_user_can( 'author' ) ){} // only if author
if( current_user_can( 'contributor' ) ){} // only if contributor
if( current_user_can( 'subscriber' ) ){} // only if subscriber
?>
More info here: How To Check If User Is Administrator Or Editor In WordPress
use this code, I hope this solve your problem
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
echo trim($user_role);
$user=wp_get_current_user();
if(in_array("administrator", $user->roles)){
//user role is admin
}
When I attempt the following I get Warning: Cannot modify header information - headers already sent by......
I'm trying to require a user to be logged in before they access my page with the shortcode on it.
What am I missing? Thanks a million for any help you can offer.
add_shortcode( 'guest-posts', 'guestposts_shortcode' );
function guestposts_shortcode( $atts ) {
auth_redirect();
}
It may work if you parse the post content before to render it. Then you should check if you find the shortcode inside the content.
Here is a small generic function to check it :
function has_shortcode($shortcode = '') {
global $post;
if (!$shortcode || $post == null) {
return false;
}
if ( stripos($post->post_content, '[' . $shortcode) !== false ) {
return true;
}
return false;
}
Now we have to create a function that will check for our specific shortcode :
function unlogged_guest_posts_redirect() {
if(has_shortcode('guest-posts') && !is_user_logged_in()) {
auth_redirect();
}
}
Then we have to hook our function (I think this can work in "wp" hook, but you can try anohter if it does not) :
add_action('wp', 'unlogged_guest_posts_redirect');
To finish, we have to ensure that the shortcode won't echo anything :
add_shortcode( 'guest-posts', 'guestposts_shortcode' );
function guestposts_shortcode( $atts ) {
return false;
}
Actually we are dealing with shortcodes but we're not using the WordPress shortcode API. This functionnality should be done using a custom field, it would be simpler !
You could instead create a special category, and hook into template_redirect:
add_filter('template_redirect', function() {
if (is_single() && in_category('special') && !is_user_logged_in())
wp_redirect(site_url('/wp-login.php'));
});