根据快捷码更改帖子类型

时间:2016-03-17 作者:user90756

是否可以在同一个函数中使用2个短代码,并根据短代码的不同仅更改函数中的post类型?

例如,当我使用all_faq 快捷码帖子类型应为Faq。当我使用wordpress_faq 那么岗位类型应该是wp-Faq. 它现在可以工作了,但是否可以在一个函数中缩短代码?就像如果all_faq 用于将职位类型更改为faq 否则,如果wordpress faq 用于将职位类型更改为wp-faq.

//shortcode NORMAL FAQ
add_shortcode( \'all_faq\', \'display_custom_post_type\' );
function display_custom_post_type(){
$args = array(

    \'post_type\' => \'Faq\',
    \'post_status\' => \'publish\',
    \'posts_per_page\' => \'-1\'
);

$string = \'\';
$query = new WP_Query( $args );
if( $query->have_posts() ){
    $string .= \'<div class="container-fluid">\';
    $string .= \'<div class="grid-container">\';
    while( $query->have_posts() ){
        $query->the_post();
            $string .= \'<div class="sub-grid">\';
            $string .= \'<div class="faq-shortcode-title">\' . get_the_title() . \'</div>\';
            $string .= \'<div class="faq-shortcode-content">\' . get_the_content() . \'</div>\';
            $string .= \'</div>\';
        }
    $string .= \'</div>\';
    $string .= \'</div>\';
}
wp_reset_postdata();
return $string;
}

//shortcode WORDPRESS FAQ
add_shortcode( \'wordpress_faq\', \'display_wordpress_faq\' );
function display_wordpress_faq(){
$args = array(
    \'post_type\' => \'wp-Faq\',
    \'post_status\' => \'publish\',
    \'posts_per_page\' => \'-1\'
);

$string = \'\';
$query = new WP_Query( $args );
if( $query->have_posts() ){
    $string .= \'<div class="container-fluid">\';
    $string .= \'<div class="grid-container">\';
    while( $query->have_posts() ){
        $query->the_post();
            $string .= \'<div class="sub-grid">\';
            $string .= \'<div class="faq-shortcode-title">\' . get_the_title() . \'</div>\';
            $string .= \'<div class="faq-shortcode-content">\' . get_the_content() . \'</div>\';
            $string .= \'</div>\';
        }
    $string .= \'</div>\';
    $string .= \'</div>\';
}
wp_reset_postdata();
return $string;
}

2 个回复
SO网友:mmm

回调函数有3个参数,第3个是标记名:

add_shortcode( \'all_faq\', \'commonFunction\' );
add_shortcode( \'wordpress_faq\', \'commonFunction\' );


function commonFunction($attr, $content, $tag) {

    $cores = [
        "all_faq" => "Faq",
        "wordpress_faq" => "wp-Faq",
    ];


    $args = array(
        \'post_type\' => $cores[$tag],
        \'post_status\' => \'publish\',
        \'posts_per_page\' => \'-1\'
    );


    // ...

}

SO网友:Mat_

也许你可以扭转这个问题。您所需要的只是在您的短代码中添加一个参数,这样,您就只能有一个函数和一个短代码。您可以在功能开始时使用类似的功能:

$atts = shortcode_atts( array(
    \'posttype\' => \'Faq\'
), $atts, \'all_faq\' );

$args = array(

    \'post_type\' => $atts[\'posttype\'],
    \'post_status\' => \'publish\',
    \'posts_per_page\' => \'-1\'
);
然后,您可以将您的短代码与新参数一起使用:[all_faq posttype="Faq"]

希望这有帮助。

相关推荐

SHORTCODE_ATTS()中的$ATTS参数是什么?

这个WordPress developers reference page for shortcode_atts() 国家:$atts(array)(必选)用户在shortcode标记中定义的属性。但我不理解这个定义。例如,在WP Frontend Profile 插件:$atts = shortcode_atts( [ \'role\' => \'\', ], $atts ); 据我所知,shortcode\