0

这段代码不是最优的,我正在努力寻找更好的方法。

基本上,您单击一个按钮,该按钮将 ajax 请求发送到下面列出的此文件,该文件从 WordPress 数据库中获取随机帖子。很多时候这些重复并且给人的印象是它不起作用,为了解决这个问题,我检查了当前 id = 旧 id,如果它们相同,则获得一个新帖子,但是我还没有找到在其中运行另一个 wpquery 的方法另一个查询。

<?php
    require_once('../../../wp-blog-header.php');
    header('HTTP/1.1 200 OK');
?>
    <span id="postss"><?php
        query_posts(array(
            'cat' => 39,
            'order' => 'ASC', // ASC
            'orderby' => 'rand',
            'showposts' => 1,
            ));
        $wp_query->is_archive = true; $wp_query->is_home = false;
        if (have_posts()) : while (have_posts()) : the_post();

        session_start();
        if(!isset($_SESSION['oldId']))
        {
            $_SESSION['oldId'] = get_the_id();
        }else{
            $curId = get_the_id();
            if($_SESSION['oldId'] == $curId)
            {
                header("Location: http://website.com/testimonialPull.php");     
            }else{


    the_content();
        }
        $_SESSION['oldId'] = get_the_id();
    }

    endwhile; endif;

?>

因此,发送标头请求大约需要 1 秒才能显示新帖子,而通常大约需要 2/10 秒。有没有更有效和更快的方法来做到这一点?

4

1 回答 1

0

只需像这样修改您的query_posts()电话:

$args = array(
    'cat' => 39,
    'order' => 'ASC', // ASC
    'orderby' => 'rand',
    'showposts' => 1,
);
if ( isset( $_SESSION['oldId'] ) {
    $args['post__not_in'] = array( $_SESSION['oldId'] );
}
query_posts( $args );

post__not_in参数指定将从查询中排除的 ID 数组。

如果您想阅读有关WP_Query该类及其接受的参数的更多信息(那些与接受的参数匹配query_posts()) - 请参阅 codex 页面 - Class Reference/WP Query

PP:我不明白为什么你不只是在init动作钩子上挂钩一个函数并进行查询http://website.com/?pullTestimonial=1(我不确定这是否会减慢完成过程,但这通常是我实现这一点的方式)

这是一个示例代码:

function fetch_testimonial() {
    if ( isset( $_GET['pullTestimonial'] ) ) {
        // Your code that will be executed goes here
        exit;
    }
}
add_action('init', 'fetch_testimonial', 10);

您从中获得的好处是您不需要在根目录中的某处有文件,否则您的链接不会像http://website.com/wp-content/themes/mytheme/testimonialPull.php

于 2012-11-14T11:45:36.490 回答