首先,我有一个名为events的自定义post类型,我在归档事件中编写了一个自定义查询。php文件。除了分页之外,一切都很好。
为了解决问题,我把所有的东西都去掉了,除了基本的东西,分页工作得很好。在google搜索了很多次之后,我想我的问题可能是我需要将查询作为函数写入函数中。php文件。Something like this:
function set_posts_per_page_for_events_cpt( $query ) {
if ( !is_admin() && $query->is_main_query() && is_post_type_archive( \'events\' ) ) {
$query->set( \'posts_per_page\', \'5\' );
}
}
add_action( \'pre_get_posts\', \'set_posts_per_page_for_events_cpt\' );
我完全同意这一点,但我不确定如何重写查询以使其正常工作。
This is my query:<?php
$currentdate = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
$paged = ( get_query_var( \'paged\' ) ) ? absint( get_query_var( \'paged\' ) ) : 1;
$wp_query = new WP_Query( array (
\'post_type\' => \'events\',
\'meta_query\'=> array(
array(
\'key\' => \'event_date\',
\'compare\' => \'>\',
\'value\' => $currentdate,
\'type\' => \'DATE\',
)),
\'meta_key\' => \'event_date\',
\'orderby\' => \'meta_value\',
\'order\' => \'ASC\',
\'posts_per_page\' => 12,
\'paged\' => $paged,
)
); ?>
<?php if( $wp_query->have_posts() ): ?>
<?php while( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<!-- All My Events -->
<?php endwhile;?>
<?php echo paginate_links(); ?>
<?php endif; ?>
如果我在这方面完全错了,请告诉我。非常感谢您的任何帮助或指出正确的方向。
SO网友:Mike
所以我通过在函数中添加这个函数来实现这一点。php
// Custom query for events
function set_posts_per_page_for_events_cpt( $query ) {
if ( !is_admin() && $query->is_main_query() && is_post_type_archive( \'events\' ) ) {
// set date
$currentdate = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
$meta_query = array(
array(
\'key\'=>\'event_date\',
\'compare\' => \'>=\',
\'value\'=> $currentdate,
\'type\' => \'DATE\',
),
);
$query->set(\'meta_query\', $meta_query);
$query->set( \'posts_per_page\', \'12\' );
$query->set( \'meta_key\', \'event_date\' );
$query->set( \'orderby\', \'meta_value\' );
$query->set( \'order\', \'ASC\' );
}
}
add_action( \'pre_get_posts\', \'set_posts_per_page_for_events_cpt\' );