Post file using wp_remote_post

WordPress HTTP API standardize the HTTP requests to allow using a single function instead of providing different method supports based on web hosting.

Instead of directly using curl or any other method, you can use the WordPress HTTP API.

wp_remote_post allows you to send a HTTP post request, but it doesn’t support sending file over to the URL.

For Posting a file using wp_remote_post, you can use the hack given below, It was originally  suggested by David Anderson in WordPress mailing list.

$local_file = $file_path;
$post_fields = array (
 'name' => 'value'
);
$boundary = wp_generate_password( 24 );
$headers  = array(
 'content-type' => 'multipart/form-data; boundary=' . $boundary
);
$payload = '';
// First, add the standard POST fields:
foreach ( $post_fields as $name => $value ) {
 $payload .= '--' . $boundary;
 $payload .= "\r\n";
 $payload .= 'Content-Disposition: form-data; name="' . $name .
'"' . "\r\n\r\n";
 $payload .= $value;
 $payload .= "\r\n";
}
// Upload the file
if ( $local_file ) {
 $payload .= '--' . $boundary;
 $payload .= "\r\n";
 $payload .= 'Content-Disposition: form-data; name="' . 'upload' .
'"; filename="' . basename( $local_file ) . '"' . "\r\n";
 //        $payload .= 'Content-Type: image/jpeg' . "\r\n";
 $payload .= "\r\n";
 $payload .= file_get_contents( $local_file );
 $payload .= "\r\n";
}
$payload .= '--' . $boundary . '--';
$response = wp_remote_post( $req,
 array(
  'headers'    => $headers,
  'body'       => $payload,
 )
);

It works perfectly fine, however for bigger file size it might have some issues.

MAMP or the Easyengine Vagrant

Well to be honest, I’ve never even tried using MAMP because I never felt to use it, so I can’t give you Pros or Cons of MAMP.

I’ve recently switched to Vagrant with Easyengine – A good alternative to manual WordPress setup and things are so easy for site development over a Mac that I never felt the need of MAMP. However I’ve been reading the Pros and Cons of Vagrant over MAMP, you can refer it on From MAMP to Vagrant

You can easily setup the Vagrant using their installation guide.

Once you are done settings up the Vagrant and the Easyengine, the whole WordPress site setup takes less than a minute (On a 8Mbps Connection) or few seconds (On Digital Ocean server), as the only time Easyengine takes, is to download the WordPress and rest of the setup is so breezy. It is really handy for WordPress Developers.

Easyengine uses Nginx server and not Apache, which is considered to better in terms of performance. There are lots of site management options for a production server, you can get all the details on their site : https://rtcamp.com/easyengine/

– MAMP or the Easyengine Vagrant

 

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 scripts and styles only in pages with shortcode

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

Loading all those shortcode specific scripts 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') );