Reputation: 2068
I am in need of creating a report on our WordPress pages. The report should consist of the page title and its URL, linked to the actual page. However, we dont want to list all pages. We need to filter them based on Draft or Published.
Is this possible to list pages filtered by Draft or Published? (the author does not matter)
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//display title, url filtered by draft or published
} // end while
} // end if
?>
Upvotes: 0
Views: 684
Reputation: 2011
There are two ways to do this one is using get_posts
while second one is using WP_Query
Argumnet for both ways it will be same.
$args=array(
'posts_per_page' => -1,
'post_type' => 'page',
'post_status' => array( 'publish', 'draft' )
);
Method - 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>";
}
Method - 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;
Upvotes: 1
Reputation: 779
Yes, you have to use WP Query and pass your arguments to display the pages which are are published or drafted:
<?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; ?>
the key here is to use post_status
to filter out the posts.
Upvotes: 1