我想使用短代码显示自定义帖子
我的自定义帖子代码位于 -
/ 自定义帖子 /
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'service_items',
array(
'labels' => array(
'name' => __( 'Service Items' ),
'singular_name' => __( 'Service Items' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Service Items' ),
'edit_item' => __( 'Edit Service Items' ),
'new_item' => __( 'New Service Items' ),
'view_item' => __( 'View Service Items' ),
'not_found' => __( 'Sorry, we couldn\'t find the Service Items you are looking for.' )
),
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'menu_position' => 14,
'has_archive' => false,
'hierarchical' => false,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'custompost_id' ),
'supports' => array( 'title', 'editor', 'custom-fields','thumbnail' )
)
);
}
短信代码如下 -
function service_item_shortcode() {
$args = array(
'post_type' => 'service_items',
'order' => 'DESC',
'posts_per_page'=> -1
);
$service_items = new WP_Query( $args );
if( $service_items->have_posts() ):
while ( $service_items->have_posts() ) : $service_items->the_post();
$service_output = '<div class="span3 serv">';
$service_output .='<div class="serv-img">' ;
$service_output .=get_the_post_thumbnail( $service_items->post->ID, service-image) ;
$service_output .='</div>';
$service_output .= '<h3>' . get_the_title() . '</h3> ';
$service_output .= '<p>' . get_the_content() . '</p> ';
$service_output .= '</div>';
endwhile;
endif;
return $service_output;
}
add_shortcode( 'service_item', 'service_item_shortcode' );
我想在每个页面上显示4个自定义帖子项目。 但是当我把[service-item]短代码输出只显示1个帖子时。
我每页需要4个帖子。请帮忙。
答案 0 :(得分:1)
您应该编写变量中所有帖子的输出,而不是在每次迭代时重置变量。为此,在循环之前定义一个空变量,并简单地将每个帖子的所有输出添加到其中。以下是适合您的更改代码(未经测试):
function service_item_shortcode() {
$service_output = '';
$paged = !empty($_GET['service_item_page']) ? absint($_GET['service_item_page']) : 1;
if (!$paged) {
$paged = 1;
}
$args = array(
'post_type' => 'service_items',
'order' => 'DESC',
'posts_per_page'=> 4,
'paged' => $paged
);
$service_items = new WP_Query( $args );
if( $service_items->have_posts() ):
while ( $service_items->have_posts() ) : $service_items->the_post();
$service_output .= '<div class="span3 serv">';
$service_output .= '<div class="serv-img">' ;
$service_output .= get_the_post_thumbnail( get_the_ID(), 'service-image');
$service_output .= '</div>';
$service_output .= '<h3>' . get_the_title() . '</h3> ';
$service_output .= '<p>' . get_the_content() . '</p> ';
$service_output .= '</div>';
endwhile;
endif;
if ($service_items->max_num_pages > 1) {
$service_output .= '<div class="pagination">';
for($i = 1; $i <= $service_items->max_num_pages; $i++) {
$service_output .= '<a href="' . add_query_arg('service_item_page', $i) . '">' . $i . '</a> ';
}
$service_output .= '</div>';
}
wp_reset_postdata();
return $service_output;
}
add_shortcode( 'service_item', 'service_item_shortcode' );