显示随机类别中的随机帖子缩略图

时间:2019-01-14 作者:nono

我的cutom帖子类型有两类:第一类第二类

我希望显示此帖子类型中的随机类别。我做了这个,它很有效:

function categorie(){    
    $global;    
    $args = array(\'type\' => \'carte\', \'taxonomy\' => \'carte-category\', \'parent\' => 0);
    $categories = get_categories($args);
    shuffle( $categories);
    $i = 0;

    foreach($categories as $category) {
        $i++;
        $categoryname=  $category->name;
        $html.= \'<h3> \'. $category->name. \'</h3>\';
        $html.= \'<p class="txtContent"> \'. $category->description. \'</p>\'; 

        if (++$i == 2) break;
    }

    return $html;
}

add_shortcode( \'categorie\', \'categorie\' );
但现在在这个随机类别中,我希望显示随机帖子的缩略图

需要明确的是:

Cat1=菜单标题:菜单1,菜单2。。。

第2类=碟片:碟片1,碟片2。。。

如果我的随机cat显示Cat1,我需要菜单1或菜单2的缩略图

我该怎么做?

2 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

您只需在代码中添加另一个查询:

function categorie_shortcode_callback() {    
    $html = \'\';
    $categories = get_categories( array(  
        // \'type\' => \'carte\', <- THERE IS NO ATTRIBUTE CALLED type FOR get_categories, SO REMOVE THAT
        \'taxonomy\' => \'carte-category\',
        \'parent\' => 0
    ));
    shuffle( $categories);

    // you also don\'t need to loop through that array, since you only want to get first one
    if ( ! empty($categories) ) {
        $category = $categories[0];
        $html.= \'<h3> \'. $category->name. \'</h3>\';
        $html.= \'<p class="txtContent"> \'. $category->description. \'</p>\'; 

        $random_posts = get_posts( array(
            \'post_type\' => \'carte\',
            \'posts_per_page\' => 1,
            \'orderby\' => \'rand\',
            \'fields\' => \'ids\',
            \'tax_query\' => array(
                array( \'taxonomy\' => \'carte-category\', \'terms\' => $category->term_id, \'field\' => \'term_id\' )
            )
        ) );
        if ( ! empty($random_posts) ) {
            $html .= get_the_post_thumbnail( $random_posts[0] );
        }
    }

    return $html;
}
add_shortcode( \'categorie\', \'categorie_shortcode_callback\' );

SO网友:wpdev

在foreach循环内部插入:

$args_query = array(
    \'order\'          => \'DESC\',
    \'orderby\'        => \'rand\',
    \'posts_per_page\' => 1,
    \'cat\' => $category->term_id,
);

$query = new WP_Query( $args_query );

if( $query->have_posts() ) {
    while( $query->have_posts() ) {
        $query->the_post();
        the_post_thumbnail();
    }
} else {
    echo \'No post found\';
}

wp_reset_postdata();