Showing posts with label wordpress. Show all posts
Showing posts with label wordpress. Show all posts

Friday, May 6, 2011

WordPress thickbox for Generated Images Solution

If you want to use Thickbox for the generated images you may get garbage values if you're using a url like http://test.com/image.php?coords=1,2,3 or http://test.com/image/ . The problem occurs when thickbox detects the url not as image. If you open the wp-includes/js/thickbox/thickbox.js file you will get a line

var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;

Image formats or urls other than the above ones will show garbage value. The solution is to edit the thickbox.js file. Do not edit the default file. Make a copy of the file and place it at your theme directory. Another Option is to obtain thickbox.js from the jQuery thickbox page. This is better than copying the WordPress included one. I will explain it a bit later. Now first add the thickbox.js file in you theme. In your functions.php file use the following code.



add_action('wp_print_scripts' , 'add_custom_thickbox');

function add_custom_thickbox(){
wp_enqueue_script('thickbox_edit' , get_bloginfo('stylesheet_directory')
 . '/thickbox.js' , 'jquery' , ' ' , true);
}


Don't forget to add the thickbox css. Now edit the thickbox.js file around Line no 72. If your url contains .php :

Replace the line
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;

with
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp|\.php$/;

Then in the line 75

Replace the line
if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif'
|| urlType == '.bmp'' )

with
if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif'
|| urlType == '.bmp' || urlType == '.php' )


There is another edit, From the whole script remove all the properties and method related with 'thickboxL10n' . This variable has been injected by wodpress as a localization process. If your copy is from jquery website your thickbox.js will have no variable 'thickboxL10n'. So It's a better option to get thickbox from the jQuery website.

If you copy download jquery from jquery website:
Replace all the "$(" with "jQuery(" .


Now click on your image and it should work now. If You face any problem you can comment here, I will try to solve your problem.


Tuesday, April 5, 2011

[SOLVED] WP-PageNavi, wp_pagenavi for custom query

WP-Pagenavi is a great plugin for paginating your WordPress Pages. Many people find it not working for custom queries like

get_posts, query_posts or for WP_Query. Today we'll solve the mystery.

Previously I edited the plugin to work for the custom queries but now the latest version has a built in feature to add your custom query object.

Suppose we make a custom query for getting some specific posts. The post ids are 1,5,8,9,10,34

$my_query = new WP_Query(
 array(
 'post_in' =>array(1,5,8,9,10,34)
 )

);

//If the total page number > 1 we will show the pagination

if($my_query->max_num_pages>1)
if(function_exists('wp_pagenavi'))
wp_pagenavi(array(
   'query' =>$my_query   
   ));

//note how  $my_query has been passed to wp_pagenavi  



You should set your posts_per_page to lower than the total page number to see the pagination. You should see the Pagination now but Wait Sailor, We are not done Yet!

You see that when you click on the second page you actually see the contents from the first page. So the solution is here.

Check your WordPress version before trying the solution


//Revised code to show posts from all pages

// page no from query

$paged = get_query_var ('paged'); 


// pass the paged value to the WP_Query

$my_query = new WP_Query( array(
 'post__in'  =>  array(1,5,8,9,10,34) ,
 'paged' => $paged
 
) );


//If the total page number > 1 we will show the pagination

if($my_query->max_num_pages>1)
if(function_exists('wp_pagenavi'))
wp_pagenavi(array(
   'query' =>$my_query   
   ));

//note how  $my_query has been passed to wp_pagenavi  



And you can use wp_pagenavi for get_posts,query_posts providing a paged value. If you're having any problem implementing, you can post your problem here. I will try to solve your problem.

Monday, March 28, 2011

wordpress cron wp_schedule_single event

In my previous post I wrote how to use
the wp_schedule_event. This post is about wp_schedule_single_event.

wp_schedule_single_event is for scheduling a single event but you can use it to execute a function more than once.

wp_schedule_single_event( $timestamp, $hook, $args = array())

$timestamp is the timestamp when we want to execute our function

$hook is the hookname(a string) that we will attach our function with.

$args is optional parameter WordPress uses to make a md5 hash string to make the schedule unique

If you want to execute your function 'my_cron_function' at the timestamp= 'timestamp' follow the code

add_action('my_hook','my_cron_func');

function my_cron_func(){
//do something here
} 

wp_schedule_single_event('timestamp', 'my_hook') 
you can use different timestamps with your hook 'my_hook' , but remember that
WordPress checks if an identical event is to be executed in 10 minutes, if so WordPress won't execute the current event.

if you use
wp_schedule_single_event(time(), 'my_hook')
wp_schedule_single_event(time()+20, 'my_hook');
WordPress will discard the second one because it's scheduled to execute to in 10 minutes of the previous identical one.
see the code the the wp-includes/cron.php

if ( $next && $next <= $timestamp + 600 )
  return;
Executing the function more than once using wp_schedule_single_event! if you use some dynamic value in the $timestamp you can make this execute more than once. for example If you use this code
wp_schedule_single_event(time()+60, 'my_hook')
when you first activate the plugin the code schedules to execute the function 1min after the current time if any visitor visits the page if you use
wp_schedule_single_event(time(), 'my_hook')
it will execute the function immediately. If you refresh your page in one minute WordPress won't execute the cron job as WordPress has set the default time interval between two cron jobs to 1 minute look for the code the wp-includes/cron.php
/*
 don't run if another process is currently running it or more
 than once every 60 sec.
*/
 if ( $flag + 60 > $local_time )
  return;
so if you want any cron job to execute maximum time you can use
wp_schedule_single_event(time(), 'my_hook');
another way to do this is to use
wp_schedule_event(time(),'every_minute','my_hook');
you have make the 'every_minute' schedule yourself see the example Here

Monday, March 21, 2011

WordPress cron explained

cron is a job scheduler in the unix-like operating systems that can be very helpful to automate tasks. . Webhosts provide cron service to execute scripts periodically.

 It is encouraged to use the webhost cron service in most of the cases because WordPress cron is actually a psudo cron service. You might want to use the functions of WordPress in your script. In that Case  you will have to load the wp-load.php file and the core WordPress functions, database classes will be available for your script.

require_once('wp-load.php');

If your host doesn't support cron, WordPress cron will be handy. You will need the WordPress cron functionalities for your plugins or for automating other tasks like auto-generating posts, sending mails, messages to users. So let's digg into the WordPress cron.

I mentioned before that WordPress cron is a "psudo cron", that means that it won't always execute the script at the real time you want. The cron job is triggered when somebody visits your website. That means if you have scheduled a function to be executed at 8am and if nobody visits your website at 8am the execution will be triggered suppost at 8:10 am when somebody has hit your site.

WordPress cron doesn't make your website slow!

May be you are thinking what if the cron-script takes a long time to be executed, will the visitors have to wait until the script is  executed. Nope! How can that be possible? If you look at the wp-cron.php file you will find a line

ignore_user_abort(true);

It's a php.ini configuration that sets that if you stop loading the site/script the script won't stop executing.

If you look at the wp-includes/cron.php file you'll find a line like this

wp_remote_post( $cron_url, 
array('timeout' => 0.01,
 'blocking' => false, 
 'sslverify' => apply_filters('https_local_ssl_verify', true)) );
 

That means WordPress will wait only 0.01 second for triggering the execution then it will abort but as you have set ignore_user_abort to true the script will be executing.This functionality is a huge advantage to execute large scripts in the WordPress cron.

Now we know the basics of WordPress cron but how will we implement this  beast?

Let's point out the most used cron WordPress functions:



wp_schedule_event($timestamp, $recurrence, $hook, $args);

Here $timestamp indicates the first time we want to execute the script. 

$recurrence is the interval between the two execution.
$hook is the hook or tag with with we attach our cron functions, $args are some optional parameters 

Let's make a plugin using the function.

<?php
/*
Plugin Name: cron-robot
Plugin URI: http://sabirul-mostofa.blogspot.com
Author: Sabirul Mostofa
Version: 0.1
*/


//adding the function to our  hook 'practice_cron_job'

add_action('practice_cron_jobs','practice_cron_func');

//calling the cron function 

if(!wp_next_scheduled('practice_cron_jobs'))
wp_schedule_event(time(),'hourly','practice_cron_jobs');


 // a function to add a option in the options table

function practice_cron_func(){
if($a=get_option('practice_cron'))
update_option('practice_cron',$a.'+');
else
add_option('practice_cron','init_value');

}

//for clearing the sceduled tasks

register_deactivation_hook(__FILE__,'deactivate_cron_hook');

function deactivate_cron_hook(){
wp_clear_scheduled_hook('practice_cron_jobs');
}
?>


what this plugin does
This plugin runs the function 'practice_cron_func' once in a hour. you
can make your own time intervals. see below in the 'what is hourly?' section.

what does the wp_next_scheduled() do?
It will take a hook as a parameter and will return the timestamp of the cron hook's next execution time 

you can add these lines in the above plugin to test:

echo wp_next_scheduled('practice_cron_jobs');
exit;

remove these lines after testing!



Why I am adding

if(!wp_next_scheduled('practice_cron_jobs'))
This is just to make sure that you are not making the same cron job again because when you are scheduling a event by
wp_schedule_event(time(),'hourly','practice_cron_jobs');
it will  schedule another event attached to the hook.


what is 'hourly'?

If you look at the function the second parameter is the time intervalbetween the executions. 'hourly' is the WordPress defined time interval. WordPress has three defined values that you can use they are
  • hourly
  • daily
  • twicedaily

You can add your defined values like 'every_minute', 'twice_a_hour' etc. This can be done by hooking a function to 'cron_schedules'. Follow the following procedure.

add_filter('cron_schedules','cron_minute');

function cron_minute($cron_schedules){
   
     $cron_schedules['every_minute'] = array(
      'interval'=> 60,
      'display'=>  __('every minute')
  );

    return $cron_schedules;
   
    } 
    
    

# Take a note that WordPress won't run cron jobs more than once a minute. see here for further details.

if we want to clear all the schedueled hooked with 'practice_cron_jobs'
use this code
wp_clear_scheduled_hook('practice_cron_jobs') ;
It will delete the cron tasks from the wp_options table

you can view the scheduled tasks attached to our defined hook by


wp_get_schedule('practice_cron_jobs');

When you deactivate plugin clear the scheduled hook which will free many scheduled events.

Use this code:


register_deactivation_hook(__FILE__,'deactivate_cron_hook');

function deactivate_cron_hook(){
wp_clear_scheduled_hook('practice_cron_jobs');

}


Recently I have been working on iappsy.com I have used cron to autogenerate the posts and it's working perfectly.

Limitations: It won't execute more than once if time limit is exceeded. For example if you have scheduled a task to do every hour and if a visior comes after 10 hours you can expect there will be 10 executions but actually it doesn't happen It'll execute only once.

WordPress won't execute cron jobs more than once a minute. see here for more details.

About Me

Web Developer From Dhaka, Bangladesh.