Password Protected Page not working after WordPress 3.4 upgrade

Few days back I was working on a site where all the pages are password protected, and after upgrade of WordPress 3.4 those pages stopped working. User can see the password promt but after submitting form with correct password page gets redirected on the same password form rather then showing protected content of the page.

Solution to this problem is to modify the filter function which works for password protected pages. “the_password_form” filter works for password proteced pages, it can be called via function.php file, here is a working example:

<?php
function custom_password_form() {
global $post;
$label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );
$o = get_post_meta($post->ID, "passwd_pg_summary_txt", true).'<br>
<form class="protected-post-form" action="' . get_option('siteurl') . '/wp-login.php?action=postpass" method="post">
' . __( "This post is password protected. To view it please enter your password below:" ) . '
<label for="' . $label . '">' . __( "Password:" ) . ' </label>
<input name="post_password" id="' . $label . '" type="password" size="20" /><input type="submit" name="Submit" value="' . esc_attr__( "Submit" ) . '" />
</form>
';
return $o;
}
add_filter( 'the_password_form', 'custom_password_form' );
?>

So what went wrong which causes this problem?Actually for versions < WordPress 3.4  form action was wp-pass.php, which in 3.4 changed to wp-login.php and wp-pass.php no more exists in WordPress 3.4+ versions.

Hope it helps!!!

 

WPoet Tip: Custom meta goes blank for custom post type

Custom post types is one of the important and useful feature wordpress have. But I found something strange when I saved custom meta in wordpress admin it went blank after some time, so I checked ajax requests in firefox firebug and found autosave works once I finished my writing in editor and left that page as its. Then searched for the solution and found we need to add a small condition which will restrict autosave to work in custom meta data. Below is the example for how it works…

WordPress api have a hook save_post which we generaly use to save custom meta

add_action('save_post', 'save_details');
function save_details(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
if($post->post_type == "mypostype")
{
 update_post_meta($post->ID, 'mypostdata', $_POST['mypostdata']);
}
}

Basically important is to add this condition

if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;

By adding above condition it return ajax request before updating custom data, so it save me and made custom post type more useful.

Code snipped: Image uploading inside your plugin using wordpress file uploader

I was recently working on a wordpress plugin and need a very small image upload feature just to upload company logo. I was thinking to use the original wordpress file uploader, as it is really very cool and easy to use as well. So after checking few code snipped’s I found the below solution:

Here is the html code for browse button,

<input id="company_logo" type="text" name="company_logo" size="36" />
<input id="upload_button" type="button" value="Upload Image" />

You are required to add these javascript libraries to achieve the lightbox effect and uploader screen

add_action('init', 'call_init');
function call_init()
{
wp_enqueue_script("jquery");
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
}

and now the actual javascript code, which will do the magic

jQuery('#upload_image_button').click(function() {
formfield = jQuery('#company_logo').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});

window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#company_logo').val(imgurl);
tb_remove();
}

Above code will open a thikbox and allow user to upload image or select from the uploaded one like one we can while adding thumnails or post images on post page. Once image gets uploaded and user presses “insert into post”, the “send to editor” function gets activated and it will copy the image url to input box you had created in the html.

This will look exactly like wordpress image uploader screen.

So upload functionality done here, but what I required was to get the image id or say attachment id once image uploaded successfully and url comes in input box, and for that there is a hook in the wordpress api which we can use while user click “insert into post” button, it is “image_send_to_editor”

add_filter('image_send_to_editor', 'image_to_editor', 20, 8);

“image_send_to_editor” hook get’s called in the background when user press ‘insert into post’ button and provides various parameter, like html, attachment id, caption of the image, title of the image, alignment of the image, url, size and alt tag of the image.
As I only need attachment id from that function to save in db and latter can use it for thumbnail generation, so I just updated a option in the database to save it.

function image_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt)
{
update_option('company_logo_id', $id);
return $html;
}

Hope this will help in image upload features of wordpress plugins. Feedback and questions are welcome here.

WordPress plugins released and got popular in 2010

We already gave adieu to year 2010 and celebrated 2011 with full joy and new hopes. Within the same flow when I look back and counted my learnings of 2010 from my work , I got WordPress in the first position.

Year 2010 gave me lots of opportunity to work in WordPress. I developed few plugins while working on client’s project and updated some existing one for my own use. So I thought lets give farewell to year 2010 by writing a post on plugins only.  So here I am listing some of the plugins which were released in 2010 and got popular (based on the download stats from wordpress.org)

  1. Wickett Twitter Widget : Wickett twitter widget is a very simple widget which show latest tweets from you twitter timeline, you just need to give a valid twitter handle, with this you can set how many tweets you want to show on the your blog .
  2. Share and Follow: Share and follow is a full social plugin which gives you option to add any social icon in your blog like facebook, twitter, linkedin, reddit, stumbler and many more. Not only this, it provides many ways and styles to match your blog’s theme.
  3. Exploit Scanner : Exploit scanner is really awesome plugin which search for suspicious data in your website and list it down for admin to take action. It searches data in your posts and comments database which is considered to be an easily accessible place in your website.
  4. Disable WordPress Plugin Updates: This plugin is really useful for  those users who gets annoyed by updates that comes for the plugins. This pugin disable all the updates that comes for any plugin in your wordpress site.
  5. Facebook Members: Facebook members is a plugin which shows list of members who already liked your site’s facebook page. New users may get attracted by this list on your website and simply like facebook page from the website itself.

While writing this post I also observed that year 2010 was a full social year, as not only people connected through various social medium but developed so many apps, plugins and addons to do the same. 2010 was wonderful social year :)

wpSimpleBackup : a simple wordpress plugin to take backups.

Search engine friendly URL for WordPress plugin

While working on one of my client’s plugin I needed to provide search engine friendly url’s for some custom functionality that was needed and existing plugin was not supporting such urls

       www.example.com/?param1=var1&param2=var2&param3=var3

but for search engine freindly url’s I want it to be like

      www.example.com/var1/var2/var3

So here I am sharing small code snippet which works perfectly for my plguin and showing nice url’s.

We need to update the theme function.php file, just add the below code in function.php file and modify variables according to your need.

<?php
add_filter('rewrite_rules_array','wp_insertRewriteRules');
add_filter('query_vars','wp_insertQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules()
{
  global $wp_rewrite;
  $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertRewriteRules($rules)
{
  $newrules = array();
  $newrules['(mytestpage)/([a-zA-Z0-9_\-]*)/([a-zA-Z0-9_\-]*)$'] =
'index.php?pagename=$matches[1]&var1=$matches[2]&var2=$matches[3]';
  $allrules = $newrules + $rules;
  return $allrules;
}

// Adding the variables  so that WP recognizes it
function wp_insertQueryVars($vars)
{
 array_push($vars, 'id');
 array_push($vars, 'var1');
 array_push($vars, 'var2');
 return $vars;
}
?>

To access these variables from plugin file use following code:

 $var1 = $wp_query->query_vars['var1'];
 $var2 = $wp_query->query_vars['var2'];

Now this will solve your plugins search engine friendly issues.

How to check for broken url in PHP

Today I was working on a site, where I  had to set a no-image placeholder on the places where images are not present, that means I need to check images are present or not, its a very simple job, but what I found was image url’s are coming from database and they all are broken links.

So now my job is to write a code which will check the images links are broken or not if broken then place a no-image place holder else image url. Here is the example on how I checked broken image url’s:

function check_url($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$data = curl_exec($ch);
	$headers = curl_getinfo($ch);
	curl_close($ch);
	return $headers['http_code'];
}
$myurl = "http://www.flickr.com/photos/thecancerus/2869110105/";
$satus = check_url($myurl);
if($satus == '200')
	echo "Its works";
else
	echo "broken url";

Hope it helps!!!

how to parse a shortcode when page is created or updated

Shortcodes in wordpress are generally use to show some cool things with very less efforts, it may be gallery, a poll or map, generally shortcode get parsed when post/page is viewed. But few days back I was working on the project where I had to parse a shortcode when post/page is created or updated, after checking some shortcode functions, I came up with solution to parse it by using do_shortcode, which will basically parse the code on the moment it get called

I had used it with pre_post_update hook and here is the example:

add_action('pre_post_update', 'parse_my_shortcode');

function parse_my_shortcode( $postid )
{
$post = get_post( $postid );
$content = $post->post_content;
do_shortcode( $content );
}

And it works really amazing!!!

Encoding video files with Zencoder API

Here is a small tutorial on how to use zencoder API for encoding your video files into different formats, this API really works great and provide the best result in very less time. You can download the PHP library which is really easy to use.

This request response works in 2 steps, 1st step where a job is created on zencoder server after your request with encoding formats, and in 2nd step you get the notification when video is encoded successfully, which ensures you that job finished successfully.

So  lets start with step 1 where you need to create a request / job for video encoding.

Creating a job/request with zencoder API:

Simply do it in this way,

$encoding_job = new ZencoderJob('
 {
   "api_key": "93h630j1dsyshjef620qlkavnmzui3",
   "input": "s3://bucket-name/file-name.avi",
   "outputs": [
    {
      "label": "web"
    }
  ]
 }
');

Where api_key is your api_key which you can get after register on zencoder.com, “input” is the file location with filename which you want  to get encoded in different formats. And most important is “Outputs” section where you can simply give many options for your output file. All the options are mentioned here http://zencoder.com/docs/api/ once your job gets created you can check it with following line of codes:

if ($encoding_job->created) {
      // Success
      echo "w00t! \n\n";
      echo "Job ID: ".$encoding_job->id."\n";
      echo "Output '".$encoding_job->outputs["web"]->label."' ID: ".$encoding_job->outputs["web"]->id."\n";
      // Store Job/Output IDs to update their status when notified or to check their progress.
 } else {
       // Failed
       echo "Fail :(\n\n";
       echo "Errors:\n";
       foreach($encoding_job->errors as $error) {
        echo $error."\n";
     }
}

If $encoding_job->created then job is created successfully else it fails and most common reason is json request was not created properly. So check your json request again if it fails.

So above is first step where you have made your request now the second step:

When zencoder completes the encoding job it will send the notification, for getting notification some parameters with the output needs to be set, following is the example for sending notification parameter with the request:

$encoding_job = new ZencoderJob('
{
   "api_key": "93h630j1dsyshjef620qlkavnmzui3",
   "input": "s3://bucket-name/file-name.avi",
   "outputs": [
   {
      "label": "web",
       "notifications":[
      {"format": "json", "url": "http://example.com/notification.php"}
     ]
   }
 ]
}
');

Once encoding completes on zencoder server it will hit the notification url for the response. For more details please check http://zencoder.com/docs/api/#notifications

Now for getting the response data, PHP library of zencoder provide a class ZencoderOutputNotification simply call in this way

$notification = new ZencoderOutputNotification();

$response_data = $notification ->catch_and_parse();

now $response_data will have the object array containing information of the job and state of the job, you can simply find the job is finished or not by this:

if( $response_data->job->state == “finished”)
{
   //do whatever processing you want.
}

Other parameters comes in the response data is:

{"job":{"state":"finished","test":true,"id":2281},
"output":{"state":"finished",
"url":"http://s3.amazonaws.com/some-example/file.webm",
"label":"WEBM","id":332222}}

HTML5 Video Player Plugin for WordPress

wp-video-js is wordpress plugin which enables post/page embed with HTML5 video player tag with the use of shortcode.
Shortcode is used to embed HTML5 video player in the content area of post:

[html5video width= "600" height = "300" splash = "http://example.com/splash.png"
src_mp4 = "http://example.com/video.mp4"
src_webm = "http://example.com/video.webm"
src_ogg = "http://example.com/video.ogg" ]

Here are list of parameters that can be set with shortcode:

width => To set the width of video screen
height => To set the height of video screen
splash => To set the splash screen of the video
src_mp4 => MP4 source of the video
src_webm => WEBM source of the video
src_ogg => OGG source of the video

Download link:  Download wordpress HTML5 Video Player plugin (4451)

How to fetch data from POST request when post variable is not known i.e. raw post data

Few days ago I was working with an Zencoder API which POST’ed the json response to my php file, but I was not sure how to catch that response and fetch the data I needed as i did not know the POST variable name, after making some search I found a way to catch it, I simply write the following statement in my response file:

$json_str = file_get_contents('php://input'); 

now $json_str will contain the string of response I get from the server

$json_arr = json_decode($json_str);

and after passing the string $json_str to json_decode function I got the response in the array of objects.

Its pretty simple now!!!

about all I have done and doing ….