JSON response in WordPress

I’ve been working in WordPress for more than a year, developing custom Themes and Plugins.
Ajax is commonly used in each of them. In general, most of us use

 json_encode()

for returning JSON response in WordPress.
Wordpress 3.5 release introduced new functions for sending JSON responses:

wp_send_json()
wp_send_json_success()
wp_send_json_error()

These functions send a JSON response back to an AJAX request, whether successful or error, and die().

Well, you’ be wondering why to use them and I’d say there is no harm in following the WordPress standards. Also, I never knew that I’ve to set the headers too, until now, which I came to know from these functions.
courtesy: Faishal

Automated WordPress installation

If you are a developer, you might need to frequently install WordPress Setups which gets quite boring with the time.

The alternative to manual installation is using some command line tool that could setup the whole thing for you. EasyEngine is one of the command line tools which helps you install your site in 5 3 minutes on Nginx server.

You can disable or enable any site on your server.

It provides you an option to setup site with Nginx Fastcgi Cache, Super Cache or Total Cache Plugin, a multisite and subdomains. Currently EasyEngine support Ubuntu 12.04 LTS and Debian.

Here is the list of commands you can refer to: Easyengine Commands

WordPress comment approval using gmail actions

Gmail recently added email actions to allow its users to take actions directly from their inbox ( good enough for lazy pals like me 🙂 ). These action allows you to review things, provide links(like you tube provides watch video button in gmail), perform other actions.

You can refer Gmail official blog for feature details.

And I’ve used the same for approving WordPress comment directly from email , thank you Incsub for the nice idea! :).

You can check the WordPress plugin: Gmail Comment Approval

Before you start using the plugin, you need to make sure that you fulfill some of the requirements to make it work with Gmail.

Install and activate the plugin

After successful installation, you need to make a dummy comment on your site.
If the comment moderation is turned on, you will receive a comment approval email.

Registering with Google

Register your site email with Gmail to allow action button to appear in the site moderator Gmail address.

  • In order to register with Gmail, you need the sample email you got for comment approval.
  • Forward the email to: [email protected] with proper subject.
  • Copy the email subject and fill up the registration form, you need to add email headers at the form end. In order to get email headers, refer Viewing Message Header in Gmail

SPF/DKIM signed emails

One of the important requirement for Gmail actions is signing of emails using SPF or DKIM, for proper security measures.

Testing email for DKIM/SPF signatures

You can check if your emails are SPF/DKIM signed or not at Mail Tester

If it is not signed properly, you need to add the signatures. If you are using VPS or a dedicated hosting like Digital Ocean you can install it using the tutorial DKIM with Postfix.

For shared hosting you need to contact hosting provider for allowing DKIM signing of emails.

If you are using DKIM signing, make sure you haven’t enabled test mode.

Also you can use 3rd party services like Postmark or Google Apps for mail delivery, they provide proper signing of emails.

As soon as your done with registration, Gmail will show you ‘Approve Comment’ in your email.

In case you are sending email to your own email, you need not to register for it, the action button appears by default.

Hope it saves some time for you.

Happy Coding.

Loading js in shortcode

Shortcode is very commonly used in WordPress sites, and a number of js and styles might be associated with it.

Loading all those shortcode specific js on each and every page will add up unnecessary load time for rest of the pages.

So you can instead load the scripts and styles conditionally.

Register script or style, you want to load dynamically:

add_action( 'wp_enqueue_scripts', 'cc_register_shortcode_script_style' );

/**
 * Register style sheet and scripts
 */
function cc_register_shortcode_script_style() {
	wp_register_style( 'my-shortcode-style', '/path/to/mystyle.css' );
	wp_register_script( 'my-shortcode-script', '/path/to/script.js', array(), '1.2.3', true );
}

And enqueue the style and scripts inside your shortcode , so that whenever the shortocde runs the scripts and styles are available on that page only.

add_shortcode('cc_shortcode', 'cc_shortcode_handler');

function cc_shortcode_handler($atts) {
	wp_enqueue_script('my-shortcode-script');
        wp_enqueue_style('my-shortcode-style');

	// actual shortcode handling here
}
 Ref: WordPress Trac Ticket

Global js variable in WordPress

If you are a WordPress Theme or Plugin developer, then you might already know this, in case you don’t, It’ll come real handy for you.

We often require some values or arrays to be available locally to theme or plugin js, If it is required for a specific JS, you can easily make it available to JS by using WordPress function:

wp_localize_script();

But in case you need the same variable to be available to multiple JS, you can do it so by hooking the JS variable at wp_head

add_action ( 'wp_head', 'my_js_variables' );
function my_js_variables(){ ?>
  <script type="text/javascript">
    var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>;      
    var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>;
    var myarray = <?php echo json_encode( array( 
         'foo' => 'bar',
         'available' => TRUE,
         'ship' => array( 1, 2, 3, ),
       ) ); ?>
  </script><?php
}

Above code echoes the variables in <head></head> section of your page, and hence you can use all the variables in your custom Javascript , wherever you want.

You can conditionally echo the code on only few templates or specific pages. Here is an example:

add_action ( 'wp_head', 'my_js_variables' );
function my_js_variables(){ 

 //for specific page templates
 $current_template =  get_page_template();

// return if there is no page template, or if the page template is other than template-x1.php or template-x2.php
 if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){  return; } ?>
  <script type="text/javascript">
    var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>;      
    var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>;
    var myarray = <?php echo json_encode( array( 
         'foo' => 'bar',
         'available' => TRUE,
         'ship' => array( 1, 2, 3, ),
       ) ); ?>
  </script><?php
}

Hope it helps someone 🙂

Cheers, Happy Coding..!!

Make update or error messages disappear automatically

It’s a very small code snippet you can use to make your user interface more user appealing.

For the all the updates or error messages, you can apply this jQuery snippet to hide the div automatically after few seconds.

jQuery(document).ready( function(){
  setInterval(function(){
        jQuery('.message.updated').hide('slow', function(){ 
            jQuery('.message.updated').remove(); 
        });
    },8000);
});

Where you can replace the selector  .message.updated with your own custom selector.
Also adjust the time span 8000 to your desired time in ms, after which the division tag disappears.

The hide(‘slow’) function provides a nice animation.

Happy Coding!

Strip Multiple Shortcodes in WordPress

The code snippet allows you to exclude particular pages or post from running the shortcode, it simply removes the shortcode instead of displaying or running it.

You can use this code to strip out one or more shortcodes, as needed.
Just call the function dot1_strip_shortcode for a particular post or category of posts or for the whole lists of posts.

Add this code to your functions.php:

global $remove_shortcode;
/**
* Strips and Removes shortcode if exists
* @global int $remove_shortcode
* @param type $shortcodes comma seprated string, array of shortcodes
* @return content || excerpt
*/
function dot1_strip_shortcode( $shortcodes ){
global $remove_shortcode;
if(empty($shortcodes)) return;

if(!is_array($shortcodes)){
$shortcodes = explode(',', $shortcodes);
}
foreach( $shortcodes as $shortcode ){
$shortcode = trim($shortcode);
if( shortcode_exists($shortcode) ){
remove_shortcode($shortcode);
}
$remove_shortcode[$shortcode] = 1;
}
add_filter( 'the_excerpt', 'strip_shortcode' );
add_filter( 'the_content', 'strip_shortcode' );
}
function strip_shortcode( $content) {
global $shortcode_tags, $remove_shortcode;

$stack = $shortcode_tags;
$shortcode_tags = $remove_shortcode;
$content = strip_shortcodes($content);

$shortcode_tags = $stack;
return $content;
}

Call the function dot1_strip_shortcode(), with proper arguments as per your condition.

e.g. :

dot1_strip_shortcode( 'Test' );
dot1_strip_shortcode( 'Test, new_shortcode' );
dot1_strip_shortcode( array('Test', 'new_shortcode') );

WordPress User Tags

Like Post Tags, WordPress User Tags Plugin allows to add taxonomies under user section, each tag has a dynamic template which displays the list of all users. Template allows you to filter the title and list style.

It can be used to categorize site users to specify their personal interests in various domains. The categories allows to filter them based on the tags.

user-taxonomies

You can register Taxonomies on the fly, and manage tags for the taxonomies.

user-tags-manager

Every user can than add tags to his profile as per their interests. In profile section user gets an option to add different tags as per their choices.

profile-tags

Tags section allows auto suggestion as well as creating new tags.

You can also `user_tags` shortocde to allow users to add tags from front end.

Post   test plugins.com

For each tag there is a page template listing all the users having same interests. There are filters available to modify listing and content for template page:

ut_template_heading : can be used to modify Template Page Heading
ut_tepmplate_content : Can be used to modify users list style,
        args => 1 , $users => list of Users
ut_template_content_empty: display custom message, if there are no users for term
user-tags-template

WordPress Download Link: User Tags

Ref: Custom User Taxonomies in WordPress