【问题标题】:Can I use pagination with the $wpdb class?我可以将分页与 $wpdb 类一起使用吗?
【发布时间】:2014-03-11 18:48:22
【问题描述】:

假设我想使用 $wpdb 类从数据库中检索图像位置,这样我就可以创建一个图像库。我有这段代码,但是当我按“下一步”时,链接似乎没有去任何地方。我错过了什么吗?

<?php
global $wpdb;
$wpdb->show_errors();
$offset = 0;
if( isset($_GET['page']) && !empty($_GET['page']) ){
$offset =  ($_GET['page']-1) * 10; // (page 2 - 1)*10 = offset of 10
}
$pics = $wpdb->get_col("SELECT pic_thumb_url FROM wp3_bp_album 
WHERE owner_type = 'user' ORDER BY title DESC
LIMIT 10 OFFSET $offset"
);
//LIMIT shows 10 results per page
//OFFSET will 'skip' this number off results. On page 1 the offset is 0 on page 2 it is 10       (if 10 results per page)
foreach($pics as $pic) :
echo '<a href ="'. '#' .'" > <img src="' . $pic . '">' . '</a>';

endforeach; 


/*
pagination
*/
?>
<a href="/community/?page=<?php echo $_GET['page']-1 ?>">previous</a>
<a href="/community/?page=<?php echo $_GET['page']+1 ?>">next</a>

我可以用这个实现分页吗?

【问题讨论】:

    标签: pagination wordpress


    【解决方案1】:

    您不能使用内置分页,但要使用分页,请在查询中使用 OFFSETLIMIT。所以,制作你自己的分页:

    <?php
    $offset = 0;
    if(isset($_GET['page']) && !empty($_GET['page']) {
        $offset =  ($_GET['page']-1) * 10; // (page 2 - 1)*10 = offset of 10
    }
    $wpdb->get_col("SELECT pic_thumb_url FROM wp3_bp_album 
        WHERE owner_type = 'user' ORDER BY title DESC
        LIMIT 10 OFFSET $offset"
    );
    //LIMIT shows 10 results per page
    //OFFSET will 'skip' this number off results. On page 1 the offset is 0 on page 2 it is 10 (if 10 results per page)
    
    /*
    pagination
    */
    ?>
    <a href="/currentpage/?page=<?php echo $_GET['page']-1 ?>">previous</a>
    <a href="/currentpage/?page=<?php echo $_GET['page']+1 ?>">next</a>
    

    并非完美无缺,它不会检查您是在第一页还是最后一页,但至少是您必须自己构建的第一个检查。

    【讨论】:

    • 对不起,我不确定你的意思。 “你不能在分页中使用构建”是什么意思,你能给我举一个偏移和限制的例子吗?谢谢!
    • Wordpress 内置了分页功能,例如:codex.wordpress.org/Function_Reference/paginate_links 它不适用于您的代码。编辑中的 SQL
    • 谢谢 Janw。我将您的建议用于偏移和限制。我现在在页面上获得了 10 个结果,但我实际上如何分页?
    • 将偏移量设为变量并用$_GET 参数填充该变量。在底部设置自己的分页,设置$_GET
    • 对不起,我对 PHP 不是很好,你能说得更具体一点,或者给我指出一个使用 $_get 的资源吗?我所知道的都与 url 查询字符串有关。
    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2023-03-25
    • 2020-08-04
    相关资源
    最近更新 更多