Php 自定义短代码拉入自定义帖子类型/类别
我创建了一个名为“故事”的自定义帖子类型,带有类别。共有5类,其中一类是“培养” 我想把所有带有“培育”类别的自定义“故事”帖子拉到一个页面中,我目前在functions.php中有这个Php 自定义短代码拉入自定义帖子类型/类别,php,wordpress,Php,Wordpress,我创建了一个名为“故事”的自定义帖子类型,带有类别。共有5类,其中一类是“培养” 我想把所有带有“培育”类别的自定义“故事”帖子拉到一个页面中,我目前在functions.php中有这个 function register_shortcodes() { add_shortcode( 'stories', 'stories_function' ); } add_action( 'init', 'register_shortcodes' ); function stories_functi
function register_shortcodes() {
add_shortcode( 'stories', 'stories_function' );
}
add_action( 'init', 'register_shortcodes' );
function stories_function($atts) {
global $wp_query,
$post;
$atts = shortcode_atts( array(
'cat' => ''
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 3,
'post_type' => 'stories',
'orderby' => 'rand',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['cat'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
echo the_content();
}
wp_reset_postdata();
}
我使用的短代码是[stories category=“Fouring”],但没有任何内容,我在这个自定义帖子类型中使用了虚拟数据,并应用了“Fouring”类别
尝试此代码,因为您错过了通过
cat=>foundering
,并确保foundering
是该类别的slug,否则通过该类别的正确slug
function register_shortcodes() {
add_shortcode( 'stories', 'stories_function' );
}
add_action( 'init', 'register_shortcodes' );
function stories_function($atts) {
global $wp_query,
$post;
$atts = shortcode_atts( array(
'cat' => 'fostering'
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 3,
'post_type' => 'stories',
'orderby' => 'rand',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'story_category',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['cat'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
echo the_content();
}
wp_reset_postdata();
}
我刚刚用一个关于分类的截图更新了这个问题。根据你的截图,我想你的分类名称是错误的,它是自定义的帖子类型还是默认的帖子?请添加
taxonomy=>您的分类法名称
,通过查看您的屏幕截图,我想您的分类法名称是story\u category