I am having issue with WP_Query, My scenario:
a) Using http://wordpress.org/extend/plugins/countries/
b) Using WP_Query to fetch countries and their codes only.
c) resetting query properly.
d) using custom post type
e) using meta boxes
f) using get_post_type() to retrieve the custom post type.
Here is code snippet:
$query_args = array(
'post_type' => 'countries',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$countries_query = new WP_Query($query_args);
$countries_array = array();
if ($countries_query->have_posts()):
while ($countries_query->have_posts()) :
$countries_query->the_post();
$country_meta = get_post_custom($post->ID);
$country_code = $country_meta['country_code'][0];
//$countries_array[$country_code] = $post->post_name;
$countries_array[$country_code] = $post->post_title;
endwhile;
endif;
wp_reset_postdata();
/*
* sorting countries alphabatically, keeps keys intact with "ksort"
*/
ksort($countries_array);
$GLOBALS['custom_countries'] = $countries_array;
and I am adding meta box to my custom post type, using
if (get_post_type() == 'my_custom_post_type'):
add_my_meta_box_for_custom_post_type();
endif;
and get_post_type() returns “countries” instead of global $post which is in this case my “my_custom_post_type”.
Is there anything wrong with my code?????
Please reply only if you have specific answers not general answers or speculations.
If you look at the source and the Codex page for
get_post_type
you will see that returns the type of the “current post” unless you pass it a post ID or post Object.get_post_type
should work without a parameter if you are running that code on the post edit page(s) generated by WordPress for post types. Anywhere else and that is not guaranteed. It isn’t possible to give you specifics because your questions doesn’t contain specific enough information, but I am fairly sure that is the problem you are having with the code.That said, @WPThemes is right. That check is not necessary. That answer should probaly solve things for you (so pick it).
Additional notes: If you register your metaboxes on a callback (@WPThemes’ answer) when you register the post type you can dispense with the
is_admin
check. The boxes will register when they are needed. you can also hook directly toadd_meta_boxes_{post-type}
.You don’t need to check for custom post type to add meta boxes. You only need to specify which custom post type you’d like the add_meta_box() function you’d like to run it on. Something like this: