Wordpress - Query if a custom post type has any posts - from outside the loop
I'm making a restaurant menu using custom post types for the different menu sections. I used the excellent Custom Post Types UI plugin and the Verve Meta Boxes plugin. I'm then flowing them out into separate loops with several segments of the below code:
<?php
$hotfood = get_posts( array('post_type' => 'hotfood', 'posts_per_page' => -1) );
foreach ($hotfood as $post) :
setup_postdata($post);
?>
<dl>
开发者_运维百科 <dt>
<strong><?php the_title_attribute(); ?></strong>
<span>£<?php echo get_post_meta($post->ID, 'price', true) ?></span>
</dt>
<?php
$key = 'description';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') {
echo '<dd>'.$themeta.'</dd>';
}
?>
</dl>
But then above that, I'm trying to get an if
asking whether there are any posts within a custom post type that I've defined.
I've tried things like
<?php if(get_posts ('post_type' => 'hotfood')
echo '<h2>Hot Food</h2>';
?>
and
<?php $args = array
(
'post_type' => 'hotfood',
'numberposts' => -1'
);
$hotfoodpresent = get_posts($args);
if($hotfoodpresent) echo '<h2>Hot Food</h2>';
?>
but neither of those seem to work. I think I've trawled through the Wordpress Codex and have spent quite a lot of time trying to decipher the issue.
Any help would be greatly appreciated.
UPDATE: Sorry, totally sorted. I was overcomplicating things. A simple
<?php
$hotfoodpresent = get_posts(
[
'post_type' => 'hotfood',
'posts_per_page' => 1,
'fields' => 'ids'
]
);
if ($hotfoodpresent) {
echo '<h2>Hot Food</h2>'
};
worked perfectly.
I was overcomplicating things. A simple
<?php
$hotfoodpresent = get_posts(
[
'post_type' => 'hotfood',
'posts_per_page' => 1,
'fields' => 'ids'
]
);
if ($hotfoodpresent) {
echo '<h2>Hot Food</h2>';
};
worked perfectly.
精彩评论