WordPress Useful Codes

As we know that wordPress provides a lot of predefined functions which we can use to get our work done easily. In our today’s post, we will get all those WordPress Useful Codes together so that anyone can use these codes anytime at the time of development. Generally, we don’t remember the function name exactly and due to that, we have to google that. Sometimes we get the correct result in out search but sometimes it takes a lot of time to search things. I had tried to provide all the daily use code by developer in one post. You can use the code anywhere in your project. Lets have the list of codes with some description:

1. Get all users with role ‘Administrator’

<?php
$user_query = new WP_User_Query( array( 'role' => 'Administrator' ) );
if ( ! empty( $user_query->results ) ) {
  foreach ( $user_query->results as $user ) {
    echo '<p>' . $user->display_name . '</p>';//display name of user with role Administrator
  }
} else {
  echo 'No users found.';
}
?>

Some wordpress useful codes and posts link

2. WordPress Useful Codes – Display only authors

<?php
$user_query = new WP_User_Query( array( 'who' => 'authors' ) );
if ( ! empty( $user_query->results ) ) {
	foreach ( $user_query->results as $user ) {
		echo '<p>' . $user->display_name . '</p>';
	}
} else {
	echo 'No users found.';
}
?>

OR

<?php
$args = array(
	'meta_key'     => 'user_level',
	'meta_value'   => '0',
	'meta_compare' => '!=',
	'blog_id'      => 0
);
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->results ) ) {
	foreach ( $user_query->results as $user ) {
		echo '<p>' . $user->display_name . '</p>';
	}
} else {
	echo 'No users found.';
}
?>

3. Disable plugin update for a specific plugin only

Although there can be many ways to do this but I am giving away two of them

Way 1 : Add this code in your plugin root file:

add_filter('site_transient_update_plugins', 'remove_update_notification');
function remove_update_notification($value) {
     unset($value->response[ plugin_basename(__FILE__) ]);
     return $value;
}

Way 2: Adding code to theme’s functions.php

function my_filter_plugin_updates( $value ) {
   if( isset( $value->response['wp-faker/wp-faker.php'] ) ) {        
      unset( $value->response['wp-faker/wp-faker.php'] );
    }
    return $value;
 }
 add_filter( 'site_transient_update_plugins', 'my_filter_plugin_updates' );

Note : wp-faker is the name of  folder and wp-faker.php is the root file name of plugin.

4. Show errors:

Scenario 1: Show errors on specific page:

Add the following code at the top of file for which you want to enable error display

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Scenario 2: show errors Globally on all wordpress pages:

Update the following code inside wp-config.php file

define( 'WP_DEBUG', true );