Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using wordpress built in thickbox without plugin

I am trying to use the built in thickbox in wordpress in my theme. I am trying to make it so all pictures that I add through the admin automatically have the thickbox function. I tried putting this in the functions.php but it did not work:

function fb_add_thickbox($content){
$content = preg_replace('/<a(.*?)href="(.*?).(jpg|jpeg|png|gif|bmp|ico)"(.*?)><img/U', '<a$1href="$2.$3" $4 class="thickbox"><img', $content);
return $content;
}
add_filter('the_content', 'fb_add_thickbox', 2);
like image 587
Davey Avatar asked Jul 08 '11 23:07

Davey


1 Answers

Assuming that your code is actually working - (is your markup actually getting filtered?) - this will fail, as thickbox has not been activated. You must manually inject it:

As @Alexcp noted - you must register and enqueue the javascript and css manually (outside of the admin section). In addition to your preg_replace function, add the following to your template's Functions.php.

// register scripts 
if (! function_exists(thickbox_register){
function thickbox_register() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery','http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js');
    wp_register_script( 'thickbox', 'path to thickbox'.thickbox.js, 'jquery');
    }  
}   
add_action('init', 'thickbox_register');

//print the now registered scripts 
if (! function_exists(thickbox_enqueue){
function thickbox_enqueue() {
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'thickbox' );
    }  
}
add_action('wp_print_scripts', 'thickbox_enqueue');

// do the same for css 
if (! function_exists(thickbox_style_enqueue){
function thickbox_style_enqueue() {
    wp_register_style( 'thickbox', 'path to css'.thickbox.css );
    wp_enqueue_style( 'thickbox' );
    }  
}
add_action('wp_print_styles', 'thickbox_style_enqueue');

Note that paths can be obtained several ways - but something like bloginfo('url'); should get you started.

If you still have problems, use FireBug or something like it to ensure that thickbox is getting registered properly in the jquery object of the DOM.

Hope that helps

like image 149
Bosworth99 Avatar answered Oct 31 '22 21:10

Bosworth99