Wordpress - カスタム投稿タイプに投稿があるかどうかをループの外側からクエリする
-
26-09-2019 - |
質問
さまざまなメニューセクションにカスタム投稿タイプを使用してレストランメニューを作成しています。私は優れた Custom Post Types UI プラグインと Verve Meta Boxes プラグインを使用しました。次に、以下のコードのいくつかのセグメントを含む個別のループにそれらを流し込んでいます。
<?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>
しかし、それ以上に、私は if
定義したカスタム投稿タイプ内に投稿があるかどうかを尋ねます。
私は次のようなことを試しました
<?php if(get_posts ('post_type' => 'hotfood')
echo '<h2>Hot Food</h2>';
?>
そして
<?php $args = array
(
'post_type' => 'hotfood',
'numberposts' => -1'
);
$hotfoodpresent = get_posts($args);
if($hotfoodpresent) echo '<h2>Hot Food</h2>';
?>
しかし、どちらもうまくいかないようです。私は Wordpress Codex をくまなく調べ、問題を解読するのにかなりの時間を費やしたと思います。
ご協力をいただければ幸いです。
アップデート:申し訳ありませんが、完全に整理されました。物事を複雑にしすぎていました。シンプルな
<?php
$hotfoodpresent = get_posts(
[
'post_type' => 'hotfood',
'posts_per_page' => 1,
'fields' => 'ids'
]
);
if ($hotfoodpresent) {
echo '<h2>Hot Food</h2>'
};
完璧に機能しました。
解決
物事を複雑にしすぎていました。シンプルな
<?php
$hotfoodpresent = get_posts(
[
'post_type' => 'hotfood',
'posts_per_page' => 1,
'fields' => 'ids'
]
);
if ($hotfoodpresent) {
echo '<h2>Hot Food</h2>';
};
完璧に機能しました。
所属していません StackOverflow