Objective: 以允许分页的方式查询和循环页面的第三级“孙子”。
以下是我正在使用的代码(不包括分页):
// Get the ID of the first generation
$gen1_ids = $post->ID;
// Query for second generation IDs
$gen2 = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_parent IN ($gen1_ids) AND $wpdb->posts.post_type = \'page\' AND $wpdb->posts.post_status = \'publish\' ORDER BY $wpdb->posts.ID ASC" ); // Test ordering by title
// Implode the results for further use
$gen2_ids = implode( $gen2,\', \' );
// Now, query for third generation IDs using second generation IDs
$gen3 = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_parent IN ($gen2_ids) AND $wpdb->posts.post_type = \'page\' AND $wpdb->posts.post_status = \'publish\' ORDER BY $wpdb->posts.ID ASC" );
$args = array(
\'post__in\' => $gen3,
\'post_type\' => \'page\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 5,
\'paged\' => get_query_var(\'paged\')
);
$results = null;
$results = new WP_Query( $args );
if( $results->have_posts() ) {
while ( $results->have_posts() ) : $results->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>" class="img"><img src="#"></a>
<div class="text">
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<p>...</p>
</div>
</li>
<?php endwhile;
} /* end if */ ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
两年前,我在WordPress上修改了一个支持问题的答案中的代码。组织论坛。代码正在运行。
有没有办法做得更好?
最合适的回答,由SO网友:Matthew Boynes 整理而成
你在正确的轨道上。通过连接post_parent
. 将此函数放入函数中。php文件,然后在模板中可以替换WP_Query
使用呼叫$results = wpse_84810_get_grandchildren();
, 将if子句更改为if( $results && $results->have_posts() )
, 然后继续使用剩下的模板代码。
function wpse_84810_get_grandchildren( $grandparent_id = false ) {
global $wpdb;
if ( !$grandparent_id )
$grandparent_id = get_the_ID();
$grandchildren_ids = $wpdb->get_col( $wpdb->prepare( "SELECT p1.ID FROM {$wpdb->posts} AS p1 INNER JOIN {$wpdb->posts} AS p2 ON p1.post_parent = p2.ID WHERE p2.post_parent = %d", $grandparent_id ) );
if ( $grandchildren_ids ) {
return new WP_Query( array(
\'post__in\' => $grandchildren_ids,
\'post_type\' => \'page\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 5,
\'paged\' => get_query_var( \'paged\' ) ? get_query_var( \'paged\' ) : 1
) );
}
return false;
}