我需要在WordPress页面上创建报告。该报告应包含页面标题及其链接到实际页面的URL。但是,我们不想列出所有页面。我们需要根据草稿或已发布对其进行过滤。
是否可以列出按草稿或发布过滤的页面? (作者无所谓)
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//display title, url filtered by draft or published
} // end while
} // end if
?>
答案 0 :(得分:1)
是的,您必须使用WP Query并传递参数以显示已发布或草拟的页面:
<?php
$args = array(
'post_type' => 'page',
'post_status' => array( 'publish', 'draft' )
);
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
这里的关键是使用post_status
来过滤帖子。
答案 1 :(得分:1)
有两种方法可以做到这一点:一种是使用get_posts
,而第二种是使用WP_Query
Argumnet在两种方式上都是相同的。
$args=array(
'posts_per_page' => -1,
'post_type' => 'page',
'post_status' => array( 'publish', 'draft' )
);
方法-1-get_posts()
$pageslist = get_posts( $args );
foreach($pageslist as $key=>$val)
{
$pageid=$val->ID;
$link= get_permalink($pageid);
$title=$val->post_title;
echo "Page title: {$title}<br>Page id: {$pageid}<br> Link:{$link}<br><br>";
}
方法-2-WP_Query
$page_data = new WP_Query( $args );
if ( $page_data->have_posts() ) :
while ( $page_data->have_posts() ) : $page_data->the_post();
?>
<p> Page Title:
<?php the_title();?></p>
<p> Page ID:
<?php the_ID();?></p>
<p> Page link:
<?php the_permalink();?></p>
<br><br>
<?php
endwhile;
wp_reset_postdata();
else : esc_html_e( 'Sorry, no posts matched your criteria.' );
endif;