Last active
October 30, 2018 19:36
-
-
Save mahdi-alavi/13e5022f3c0386e180e2f9f154734bc8 to your computer and use it in GitHub Desktop.
wordpress: custom pagination with wpdb get_results
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
global $wpdb; | |
$sql = " | |
SELECT $wpdb->posts.* | |
FROM $wpdb->posts | |
WHERE $wpdb->posts.post_status = 'publish' | |
AND $wpdb->posts.post_type = 'post' | |
AND $wpdb->posts.post_date < NOW() | |
ORDER BY $wpdb->posts.post_date DESC | |
"; | |
$current = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1; | |
$post_per_page = get_option( 'posts_per_page' ); | |
$offset = ( $current * $post_per_page ) - $post_per_page; | |
$all_results = $wpdb->get_results( $wpdb->prepare( $sql ), OBJECT ); | |
$total = $wpdb->num_rows; | |
$result = $wpdb->get_results( $wpdb->prepare( $sql . 'LIMIT %d, %d', $offset, $post_per_page ), OBJECT ); | |
if ( $sql ) { | |
global $post; | |
foreach ( $sql as $post ) { | |
setup_postdata( $post ); | |
// custom loop | |
} | |
$args = array( | |
'base' => add_query_arg( 'paged', '%#%' ), | |
'total' => ceil ( $total / $post_per_page ), | |
'current' => $current | |
); | |
echo paginate_links( $args ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment