有人可以帮我简化下面的WP_Query吗?它们具有完全相同的结构,但是一个针对未来,一个针对过去的事件。
<?php
$future = date('Ymd', strtotime("+1 year"));
$now = date('Ymd', strtotime("now"));
$past = date('Ymd', strtotime("-1 year"));
?>
<?php
$args_future = array(
'post_type' => 'event',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => array($now, $future),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$query_future = new WP_Query($args_future);
?>
<?php
echo '<h2>Future events</h2><ul class="future-events">';
while($query_future->have_posts()) {
$query_future->the_post();
echo '<li><a href="'.get_permalink($post->ID).'">'.get_the_title().'</a></li>';
} echo '</ul>'; wp_reset_postdata();
?>
<?php
$args_past = array(
'post_type' => 'event',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => array($past, $now),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$query_past = new WP_Query($args_past);
?>
<?php
echo '<h2>Past events</h2><ul class="past-events">';
while($query_past->have_posts()) {
$query_past->the_post();
echo '<li><a href="'.get_permalink($post->ID).'">'.get_the_title().'</a></li>';
} echo '</ul>'; wp_reset_postdata();
?>
答案 0 :(得分:0)
你的代码太糟糕了。如果你想保持可读性,在这种情况下将它拆分成几个循环几乎是不可避免的。我在这里所做的只是将你的代码组织成一个多维数组。这是未经测试的,但应该让你开始:
<?php
$future = date('Ymd', strtotime("+1 year"));
$now = date('Ymd', strtotime("now"));
$past = date('Ymd', strtotime("-1 year"));
$args = array(
'future'=>array(
'ul_class'=>'future-events',
'label'=>'Future Events',
'query_args'=>array(
'post_type' => 'event',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => array($now, $future),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
)
),
'past'=>array(
'ul_class'=>'past-events',
'label'=>'Past Events',
'query_args'=>array(
'post_type' => 'event',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => array($past, $now),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
)
)
);
foreach($args as $arg){
$q = new WP_Query($arg['query_args']);
printf('<h2>%s</h2><ul class="%s">', $arg['label'], $arg['ul_class']);
while($q->have_posts()) : $q->the_post();
echo '<li><a href="'.get_permalink($post->ID).'">'.get_the_title().'</a></li>';
endwhile;
echo '</ul>';
}
wp_reset_postdata();
?>