0

I have a simple custom query driven by get_posts:

<ul>
<?php 
$args = array('post_type' => 'event', 'numberposts' => 6 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); 
    echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endforeach;
wp_reset_postdata();
?>
</ul>

However, there's a need to access this custom loop's query object - the one which is accessible by default if you do custom loops using new WP_Query method. (This is needed to get connected posts of other CPTs, mechanism driven by the excellent Posts2Posts plugin's each_connected.) Is it possible to get to the query object from get_posts? Or the only way to do this is to remake the loop in the new WP_Query style?

1

You can filter any WP query using pre_get_posts(). The (sometimes) tricky part is that it is run against all queries of WP so you need to pinpoint your query using WP conditionals (is_admin(), is_page(), is_archive(), etc... ).

You'll find a few useful examples on that page, too.

  • Ah, good point, I suppose if one did eg if ( ! $query->is_main_query() && $query->get( 'post_type' ) == 'event' && $query->get( 'numberposts' ) == 6 ) { one would be almost sure to isolate the query. – bonger Jan 25 '15 at 11:31
  • That's it, thanks. We setup pre_get_posts in functions.php and then are able to change the appropriate query parameters such as connected_type and connected_items. Thanks! – certainlyakey Jan 29 '15 at 6:19
0

Yes, I think the only way is (See Andrei Gheorghiu's answer) If you choose to remake the loop, the slightly tricky bit is to make the $args array the same as get_posts()'s defaults:

$args = array(
    'post_type' => 'event', 'posts_per_page' => 6,
    'post_status' => 'publish', // If post_type 'attachment' then 'post_status' => 'inherit'
    'orderby' => 'date', 'order' => 'DESC',
    'suppress_filters' => true,
    'ignore_sticky_posts' => true, 'no_found_rows' => true,
);
$query = new WP_Query;
$myposts = $query->query( $args );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.