1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

Monday, April 18, 2011

Programatically assiging template page wordpress

Hello readers,

I have found a very simple solutions to assign a template page to specific or all pages . According to my previous tutorial for creating the template page and placing into the wordpress current template.

For creating the template you need to add comment on the top of the page as known from my blog


/*
Template Name: new template
*/


Now what ever you want add the functionality to the page and then add header/footer as on your preference.
Now your template file is ready to run or attach to page. But now no need to copy that php file to the template folder of wordpress.
all you need to do is call the following hook



add_filter( 'page_template', 'catch_plugin_template' );


Now this will be called on every page/post load.



add_filter( 'page_template', 'catch_plugin_template' );
function catch_plugin_template($template)
{
if(is_page())
{
$template = WP_PLUGIN_DIR . '/yourpluginname/template-file.php';
return $template;
}
}

Now the above could will execute on every page and the template would be assigned to all the pages you have created.

Thank You for reading.

Thursday, April 14, 2011

Auto save problem for custom variables

Readers while developing with wordpress i found a problem with the post . I had custom variable into my metabox.

So there is a default hook to be called to save that custom variable into the database.


add_action('save_post','function_save_var');


So by default when u click publish post or update post then 'function_save_var' would be called .
So when u update the post and then close the page then this would work perfectly fine but then i din know
auto save would call this hook too .

So when my page would be open for a while all my values would reset and my functionality would fail. So
after a little search i got the solution.


function function_save_var()
{
// Function without avoiding auto save.
}


The above function would fail as it would reset everything .

but then to avoid; you need to add the following code in the start of the function


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


if the post will autosave this would directly return n do not update anything . Thus this is all solved.