【发布时间】:2016-07-19 13:15:50
【问题描述】:
我正在尝试将多个循环合并为一个,并按相关性对最终结果进行排序。
对于前一部分,我是这样做的:
// set the variables
$author_id = get_the_author_meta('ID');
$tags_id = wp_get_post_tags($post->ID);
$first_tag = $tags_id[0]->term_id;
$categories_id = wp_get_post_categories($post->ID);
// loop for same author
$by_author = new WP_Query (array(
'author' => $author_id,
'posts_per_page' => '5'
));
// add ids to array
if ($by_author->have_posts()) {
while ($by_author->have_posts()) {
$by_author->the_post();
$add[] = get_the_id();
}
}
// loop for same tag
$by_tag = new WP_Query(array(
'tag__in' => $first_tag,
'posts_per_page' => '5'
));
// add ids to array
if ($by_tag->have_posts()) {
while ($by_tag->have_posts()) {
$by_tag->the_post();
$add[] = get_the_id();
}
}
// loop for same category
$by_category = new WP_Query(array(
'category__in' => $categories_id,
'posts_per_page' => '5'
));
// add ids to array
if ($by_category->have_posts()) {
while ($by_category->have_posts()) {
$by_category->the_post();
$add[] = get_the_id();
}
}
// loop array of combined results
$related = new WP_Query(array(
'post__in' => $add,
'post__not_in' => array($post->ID),
'posts_per_page' => '10',
'orderby' => $weight[$post->ID],
'order' => 'DESC'
));
// show them
if ($related->have_posts()) {
while ($related->have_posts()) {
$related->the_post();
// [template]
}
}
这很好地将循环组合为一个。对于后一部分,我接下来要做的是在每个帖子出现时为每个帖子添加一个递增的“权重”值,以便稍后使用 'orderby' => $weight 之类的东西对它们进行排序。
例如,如果一个帖子出现在“同一作者”中,则获得 3 分,如果另一个帖子出现在同一标签中,则获得 2 分,以此类推。如果它出现在多个循环中,它应该得到组合点,即 3+2+1=6,因此被提升到最终查询的顶部。
我尝试为每个初步循环添加一个计数器,例如 $weight = +3 等,但这只会为每个帖子添加所有内容,而不是单独添加。
我还尝试在每个初步循环的末尾插入类似的内容...
$weight = 0;
if ($by_author){
foreach ($by_author as $post){
setup_postdata($post);
$weight = +10;
add_post_meta($post->ID, 'incr_number', $weight, true);
update_post_meta($post->ID, 'incr_number', $weight);
}
}
...这是最后一个
echo get_post_meta($post->ID,'incr_number',true);
但它仍然不正确。它分配了一个全局值,而我希望它们根据正在阅读的实际主要帖子而有所不同。
那么有没有办法做到这一点?
【问题讨论】:
-
我不建议在循环中进行数据库调用(
add_post_meta、update_post_meta等)。您的网站很快就会崩溃。 -
确实,那部分完全是无能和无用的。只需简单地构建以 id 为键、权重为值的数组即可正确分配分数。不过,我仍在努力解决问题。
标签: php wordpress loops foreach parameters