Usefull function for custom post type in wordpress and more
I’m gonna share someuseful function here which is really handy for custom post type. Some guys really don’t know about those functions, as i got those useful after digging some solutions for real life problem.
1. is_post_type_archive(‘POST-TYPE-NAME’), this is needed when you are checking something for post type archive/listing page like in common header/footer. we frequently use for add some js/css or some class in common places.
2. get_query_var(‘var_name’), we frequently use this to get category name, its retrieve corresponding value of given variable name. I have got this most useful when i need the slug/post_name of a post of any post type. For the last couple of month, i used below code to get last/second segment of URL of a post :
$subpath = $_SERVER['REQUEST_URI']; $tokens = explode('/', $subpath); $scn_seg = $tokens[sizeof($tokens)-3];
But that was the extra effort to get URL segment for a post, we can do it by get_query_var(), we need to pass post type name as a parameter to this function like for ‘news’ post type we will use get_query_var(‘news’).
$news_post_slug = get_query_var('news');
So for the URL : http://example.com/news/lorem-ipsum-dolor/, we can get the post slug(post_name used in DB) by get_query_var(‘news’).
3. wp_deregister_script()
sometimes we use plugins for some extra facilities like custom post type/twitter feed, plugins use wp_head() to inject its necessary js/css or others function to hook, same as for wp_footer(). wp_deregister_script
() is needed when we use our own js like jquery library. So there will be 2 jquery file when using own with wp’s native 1. and sometimes for new bee, its hard to find out why js error occurred and js functions are not working …. wp_head() renders some others links also. to avoid this type of situation, we need to remove that, we can use just wp_deregister_script('jquery');
in theme’s functions.php file.
This is useful to give a condition for admin section like below, otherwise admin panel’s may create problem:
if( !is_admin()){ wp_deregister_script('jquery'); }
Its also better to add your own library just after de-register wp’s native jquery like below :
if( !is_admin()){ wp_deregister_script('jquery'); wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"), false, '1.3.2'); wp_enqueue_script('jquery'); }
Finally its handy to remove the jQuery from your wordPress font-end/theme files, add wp_deregister_script(‘jquery’) just before wp_head() on your theme’s header.php file like below.
wp_deregister_script('jquery'); wp_head();
Will add some other WP function soon which we need frequently in development.