以下代码选择所有POST类型的IDproduct
和post
, 属于术语的category-a
或category-b
, 具有taxonomy_01
和taxonomy_02
, 分别地
$args = [
\'post_type\' => [\'product\',\'post\'],
\'posts_per_page\' => -1,
\'fields\' => \'ids\',
\'tax_query\' => [
\'relation\' => \'OR\',
[
\'taxonomy\' => \'taxonomy_01\',
\'field\' => \'slug\',
\'terms\' => \'category-a\',
\'include_children\' => false,
],
[
\'taxonomy\' => \'taxonomy_02\',
\'field\' => \'slug\',
\'terms\' => \'category-b\',
// OR by id
//\'field\' => \'term_id\', // default value
//\'terms\' => 2,
\'include_children\' => false,
],
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
$rnd = mt_rand(0, $total - 1);
$pid = $posts_ids[$rnd];
$my_post = get_post( $pid);
// display post
}
我假设条款
category-a
,
category-b
属于不同的分类法。如果没有,则
tax_query
应为:
\'tax_query\' => [
[
\'taxonomy\' => \'taxonomy_01\',
\'field\' => \'slug\',
\'terms\' => [\'category-a\', \'category-b\'],
\'include_children\' => false,
],
]
UPDATE我更改了上述代码中的变量
$post
到
my_post
. 您的代码:
$args = [
\'post_type\' => [\'product\',\'post\'],
\'posts_per_page\' => -1,
\'fields\' => \'ids\',
\'tax_query\' => [
\'relation\' => \'OR\',
[
\'taxonomy\' => \'taxonomy_01\',
\'field\' => \'slug\',
\'terms\' => \'category-a\',
\'include_children\' => false,
],
[
\'taxonomy\' => \'taxonomy_02\',
\'field\' => \'slug\',
\'terms\' => \'category-b\',
// OR by id
//\'field\' => \'term_id\', // default value
//\'terms\' => 2,
\'include_children\' => false,
],
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
// get random post_ID
$rnd = mt_rand(0, $total - 1);
$pid = $posts_ids[$rnd];
$my_post = get_post( $pid);
// display post
if ( !empty($my_post) ) : ?>
<article class="promo">
<div class="image">
<?php
if ( $my_post->post_type == \'product\' )
echo \'Product\';
else
echo \'Post\';
?>
</div>
</article>
<?php endif;
}