如何将类别选项添加到简码

How to add category option to shortcode

我是创建 wordpress 短代码的新手,并且有一个可以按照我想要的方式工作。缺少特定的东西。目前我可以在任何页面上放置以下内容 - [children] 并且它从自定义 post 类型 "children" 中提取所有 posts 的查询我想将选项添加到在短代码中添加类别 ID - 类似于 [children category="8"] 这是我目前的代码:

add_shortcode( 'children', 'display_custom_post_type' );

function display_custom_post_type(){
    $args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
    );
    $string = '';
    $query = new WP_Query( $args );
    if( $query->have_posts() ){
        while( $query->have_posts() ){
            $query->the_post();
            $string .= '<div id="childWrapper"><div id="childImage"><a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a></div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
        }
    }
    wp_reset_postdata();
    return $string;
}

二级 - 是否可以在多个类别中显示 post,但仅在 post 位于每个类别中的情况下显示。例如显示属于需要重症监护和手术类别的儿童列表。

如有任何帮助,我们将不胜感激。

您应该从 WordPress Codex 参考 Shortcode function。假设您的分类名称是 category,我对您当前的代码进行了一些更改,它应该可以按照您的要求工作。

/**
 *  [children category="5,7,8"]
 */
add_shortcode( 'children' , 'display_custom_post_type' );

function display_custom_post_type($atts) {

    $atts = shortcode_atts( array(
        'category' => ''
    ), $atts );

  //If category is multiple: 8,9,3
  $categories  = explode(',' , $atts['category']);

    $args = array(
            'post_type'     => 'children',
            'post_status'   => 'publish',
            'orderby'       => 'title',
            'order'         => 'ASC',
            'posts_per_page'=> -1,
            'tax_query'     => array( array(
                                'taxonomy'  => 'category',
                                'field'     => 'term_id',
                                'terms'     => $categories
                            ) )
        );

        $string = '';
        $query = new WP_Query( $args );

        if( ! $query->have_posts() ) {
            return false;
        }

        while( $query->have_posts() ){
            $query->the_post();
            $string .= '<div id="childWrapper"><div id="childImage"><a href="' . get_permalink() . '">' . get_the_post_thumbnail() . '</a></div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
        }
        wp_reset_postdata();

        return $string;
}