Conditionally display post using publish status

Posted by admin on 10.20.08 5:50PM under wordpress snippets

I needed an “alert” type post– a permanent, uniquely styled post, identified by post ID, that could be displayed and hidden easily through the admin interface. I know there are plugins that almost accomplish this, but I need to have my non-technical end users edit and publish an existing post. To do this I needed to access the “publish” status, but for the longest time couldn’t get the code to work. The problem is that the post status assignments in the admin interface don’t clearly correspond with the coded post_status arguments. ‘Unpublished’ in the WP admin interface uses ‘draft’ as the argument in the code. And…here is something that will examine the post arguments outside the loop.

The example code I found on the Wordpress site shows posts with attachments:

<?php

$args = array(
	'post_type' => 'attachment',
	'numberposts' => null,
	'post_status' => null,
	'post_parent' => null, // any parent
	);
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $post) {
	        setup_postdata($post);
		the_title();
		the_attachment_link
                      ($post->ID, false);
		the_excerpt();
	}
}

?>

Here I’ve modified it to show ‘unpublished’ posts:

<?php

$args = array(
	'post_status' => 'draft',
	);
$draft = get_posts($args);
if ($draft) {
	foreach ($draft as $post) {
		setup_postdata($post);
		the_title();
		the_content();
	}
}

?>

Now I can use this with an if statement and a post ID to add the alert post, and all my end user has to do is set the post to publish/unpublish. My final code uses category name, post status, AND the post ID (a bit of overkill) but you can see how the arrays work. The “firstpost” div allows you to uniquely style the alert:

<?php query_posts('category_name=swim-team'); ?>
<?php
	$args = array(
		'category_name' => 'swim-team',
		'post_status' => 'publish',
		'include' => "129",
	);
	$draft = get_posts($args);
	if ($draft) {
		foreach ($draft as $post) { ?>
		<div id="firstpost">
	<?php
		setup_postdata($post);?>
		<h2><?php the_title(); ?></h2>
		<?php the_content(); ?>
		</div>
		<?php
	}
}
?>

Leave a Reply