方法三:标签相关,SQL获取
获取相关文章的原理与方法一相似,不过在获取文章的时候是以SQL语句来直接读取数据库,从而随机获取6篇相关文章记录,而不是WordPress的函数query_posts().
$post_tags = wp_get_post_tags($post-ID);
if ($post_tags) {
foreach ($post_tags as $tag)
{
// 获取标签列表
$tag_list[] .= $tag-term_id;
}
// 随机获取标签列表中的一个标签
$post_tag = $tag_list[ mt_rand(0, count($tag_list) - 1) ];
$related = $wpdb-get_results("
SELECT {$wpdb-prefix}posts.post_title, {$wpdb-prefix}posts.guid
FROM {$wpdb-prefix}posts, {$wpdb-prefix}term_relationships, {$wpdb-prefix}term_taxonomy
WHERE {$wpdb-prefix}posts.ID = {$wpdb-prefix}term_relationships.object_id
AND {$wpdb-prefix}term_taxonomy.taxonomy = 'post_tag'
AND {$wpdb-prefix}term_taxonomy.term_taxonomy_id = {$wpdb-prefix}
term_relationships.term_taxonomy_id
AND {$wpdb-prefix}posts.post_status = 'publish'
AND {$wpdb-prefix}posts.post_type = 'post'
AND {$wpdb-prefix}term_taxonomy.term_id = '" . $post_tag . "'
AND {$wpdb-prefix}posts.ID != '" . $post-ID . "'
ORDER BY RAND( )
LIMIT 6");
// 以上代码中的 6 为限制只获取6篇相关文章
// 通过修改数字 6,可修改你想要的文章数量
if ( $related ) {
foreach ($related as $related_post) {
?
*
title="post_title; ?"post_title; ?
* 暂无相关文章
方法四:分类相关,SQL获取
获取相关文章的原理与方法二相似,不过在获取文章的时候是以SQL语句来直接读取数据库,从而随机获取6篇相关文章记录,而不是WordPress的函数query_posts().
$cats = wp_get_post_categories($post-ID);
if ($cats) {
$cat = get_category( $cats[0] );
$first_cat = $cat-cat_ID;
$related = $wpdb-get_results("
SELECT wp_posts.post_title, wp_posts.guid
FROM wp_posts, wp_term_relationships, wp_term_taxonomy
WHERE wp_posts.ID = wp_term_relationships.object_id
AND {$wpdb-prefix}term_taxonomy.taxonomy = 'category'
AND {$wpdb-prefix}term_taxonomy.term_taxonomy_id = {$wpdb-prefix}term_relationships.term_taxonomy_id
AND {$wpdb-prefix}posts.post_status = 'publish'
AND {$wpdb-prefix}posts.post_type = 'post'
AND {$wpdb-prefix}term_taxonomy.term_id = '" . $first_cat . "'
AND {$wpdb-prefix}posts.ID != '" . $post-ID . "'
ORDER BY RAND( )
LIMIT 6");
if ( $related ) {
foreach ($related as $related_post) {
?
*
title="post_title; ?"post_title; ?
* 暂无相关文章
方法五:作者相关
该方法是获取该文章作者的其他文章来充当相关文章,代码如下:
$post_author = get_the_author_meta( 'user_login' );
$args = array(
'author_name' = $post_author,
'post__not_in' = array($post-ID),
'showposts' = 6, // 显示相关文章数量
'orderby' = date, // 按时间排序
'caller_get_posts' = 1
);
query_posts($args);
if (have_posts()) :
while (have_posts()) : the_post(); update_post_caches($posts); ?
*
title=""
* 暂无相关文章
时间效率对比
我们将用之前的一个php代码对以上各个相关文章代码执行时间进行测算,以便对以上各个的方法进行效率,给你的选择提供参考。以下是在同一篇文章中获取6篇相关文章,以上各方法最终测算的时间如下:
方法一:0.18067908287048 秒
方法二:0.057158946990967 秒
方法三:0.037126064300537 秒
方法四:0.045628070831299 秒
方法五:0.023991823196411 秒