How can I exclude a specific ID from this line of code?
I am using this code to list pages with a specific letter at the beginning of them:
$first_char = 'H';
echo '<table class="alphabet" style="border:0px;border-color:transparent;">
<tbody><tr>
<td width="100px;" style="border-color:transparent;"><span class="separator-line"></span></td>
<td style="border-color:transparent;padding-left:5px;padding-right:5px;"><span class="letter"><strong>' . $first_char . '</strong></span></td>
<td width="100px;" style="border-color:transparent;"><span class="separator-line"></span></td>
</tr>
</tbody></table>';
$postids=$wpdb->get_col($wpdb->prepare("
SELECT ID
FROM $wpdb->posts
WHERE SUBSTR($wpdb->posts.post_title,1,1) = %s
ORDER BY $wpdb->posts.post_title",$first_char));
if ($postids) {
$args=array(
'post__in' => $postids,
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1.,
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts()) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
}
wp_reset_query(); // Restore global post data stomped by the_post().
}
Basically I need to be able to exclude specific IDs from it. I've tried adding an 'exclude' => '//id' to the $args array, but that did nothing.
Solutions
On a seperate note,
'caller_get_posts'
was deprecated in version 3.1 - use
'ignore_sticky_posts'
with a boolean argument instead.
'exclude'
is not a query argument so WordPress ignores it. Post exclusion via query is done using the key
'post__not_in'
with a single
post ID
or array of IDs instead. However as @vancoder points out, the argument produces computationally expensive queries.
It's also unreasonable to apply both a
'post__in'
argument as well as a
'post__not_in'
argument as setting one implicitly describes the value of the other. A simpler and more efficient solution is available whenever you might desire to use both: just exclude post IDs from the
'post__in'
argument before applying it to the query:
$included_post_ids = $wpdb->get_col( /* ... */ );
$excluded_post_ids = [ /* ids to exclude */ ];
if( !empty( $included_post_ids ) ) {
$included_post_ids = array_diff( $included_post_ids, $excluded_post_ids );
$args = [
'post__in' => $included_post_ids,
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
'ignore_sticky_posts' => true
];
$my_query = new WP_Query( $args );
// ....
}
Information regarding query arguments can be found in the
WP_Query
reference on the Codex.