[英]Wordpress display thousands of posts
我正在一个项目中,我需要列出所有类别,子类别(子级,子级等,大约在第5级)并在其中发布。 目前,我设法使网站正常运行,但问题是该网站需要几分钟的时间才能加载。
为了清楚说明我希望网站的外观,这是一个图形:
类别子类别子类别内容子类别内容子类别您得到图片
这是代码:
<?php
function listing($parentcat, $list_id='', $list_name='', $path=false) {
// parentcat is the desired category parent category, which is defined because the function is called a few times with different sets on the page.
// list_id, list_name and path are used for purposes not related to the question
echo "<ul><li name='$list_name'><h2><a href='#$list_name'>$list_name</a></h2>";
}
$args = array(
'parent' => $parentcat,
'include' => $cat_ids,
'hide_empty' => 1,
'orderby' => 'id'
);
$categories = get_categories( $args );
echo "<ul>";
foreach ($categories as $cat) {
if ($cat->cat_name != 'Uncategorized') {
$flat_path = substr(get_category_parents($cat->cat_ID, false, ' »' ), 14);
$catnam = $cat->cat_name;
$listtitle = ($path ? $flat_path : $catnam);
echo ('<li name="' . $cat->cat_ID . '"><h2><a href="#' . $cat->cat_ID . '">' . $listtitle . '</a></h2>' );
if (get_posts( "category_name=$catnam" ) ) {
if (have_posts()) : while (have_posts()) : the_post();
if (in_category($cat->cat_ID)) {
echo '<ul><li><div>';
the_content();
echo '</div></li></ul>';
} endwhile;
else :
_e('Empty list');
endif;
}
// Here's a recursive call for the function
listing($cat->cat_ID);
echo '</li>';
}
}
echo '</ul>';
}
?>
您可能缺少帖子的“ posts_per_page”
在这里看看http://codex.wordpress.org/Function_Reference/get_posts
和
类别的“数字”
在这里看看http://codex.wordpress.org/Function_Reference/get_categories
找到解决方案! 我会自己回答,所以如果有人需要类似的东西,答案就在这里。
基本上,重点是首先创建一个包含所有类别的数组。 之后,可以简单地遍历整个数组。 这样,我们可以避免递归地使用The Loop,这可能是先前解决方案中的最大问题。
即使此解决方案确实很慢,但与过去相比却是不可思议的改进。 第一个想法在大约30秒后超时之前加载了数百个帖子顶部。 这个人会在5到10秒内获得整个网站(约1500个帖子)。 速度太糟糕了,但是使用我们的网站的方式以及从将一切划分为单独的帖子而增加的功能超过了速度问题。
$categories = get_categories('orderby=id');
$cats_by_parent = array();
foreach ($categories as $cat) {
$parent_id = $cat->category_parent;
if (!array_key_exists($parent_id, $cats_by_parent)) {
$cats_by_parent[$parent_id] = array();
}
$cats_by_parent[$parent_id][] = $cat;
}
$posts = get_posts(['posts_per_page' => 10000000]);
$posts_by_cats = array();
foreach ($posts as $post) {
$cat_id = wp_get_post_categories($post->ID)[0];
$posts_by_cats[$cat_id] = $post->post_content;
}
// Loop through the array and print with:
echo $posts_by_cats[$cat->cat_ID];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.