我创建了一个短代码,它以名为“事件”的自定义帖子类型显示任何帖子。
一切正常,但我希望它在没有可用帖子时显示一条消息。我已经尝试了一些尝试合并的东西,但它只会导致错误。
我试过了(见下文)但它没有显示消息“* no events listed at this time...”只是一个空白页面。
关于正确使用什么代码有什么建议吗?
add_shortcode('events', 'Events');
function events($atts){
$atts = shortcode_atts( array(
'category' => ''
), $atts );
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'slug',
'operator' => 'AND',
'terms' => $categories
) )
);
ob_start();
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
?>
<?php
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div><?php the_title(); ?></div>
<div><?php the_content(); ?></div>
<?php endwhile; ?>
<p>* no events listed at this time...</p>
<?php wp_reset_query(); ?>
<?php
}
$retVal = ob_get_contents();
ob_end_clean();
return $retVal;
}
我检查过你的代码不正确。
请使用以下代码。
<?php
add_shortcode( 'events', 'callback_function_name' );
function callback_function_name( $atts, $shrt_content = null ) {
// Shortcode Parameter
$atts = shortcode_atts(array(
'category' => ''
), $atts, 'events');
$categories = ! empty( $atts['category'] ) ? explode( ',' , $atts['category'] ) : '';
extract( $atts );
// Query args
$query_args = array(
'post_type' => 'event',
'post_status' => 'publish',
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'slug',
'operator' => 'AND',
'terms' => $categories
) )
);
// WP Query for Events
$post_query = new WP_Query( $query_args );
ob_start();
// If post is there
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
<div><?php the_title(); ?></div>
<div><?php the_content(); ?></div>
<?php endwhile;
} else { ?>
<p>* no events listed at this time...</p>
<?php }
wp_reset_postdata(); // Reset WP Query
$content .= ob_get_clean();
return $content;
}