Get Posts Pagination
November 17, 2024 · AI Conversations
### Step 1: Querying Posts with Pagination
Here's how you can use `WP_Query` for pagination:
<?php
// Determine the current page (1 if not specified)
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
// Define the query arguments
$args = [
'post_type' => 'post',
'posts_per_page' => 5, // Number of posts per page
'paged' => $paged,
];
// Create a new WP_Query instance
$query = new WP_Query($args);
// Check if there are posts
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<p><?php the_excerpt(); ?></p>
<?php endwhile; ?>
<!-- Pagination Links -->
<div class="pagination">
<?php
echo paginate_links([
'total' => $query->max_num_pages,
'current' => $paged,
]);
?>
</div>
<?php wp_reset_postdata(); // Reset the global $post object
else :
echo '<p>No posts found.</p>';
endif;
?>
### Explanation
– **`paged`**: Gets the current page number. If not set, it defaults to page 1.
– **`posts_per_page`**: Defines how many posts you want per page.
– **`WP_Query`**: Fetches posts based on the defined arguments.
– **`paginate_links()`**: Generates pagination links.
### Step 2: Adding Support for Pretty Permalinks
Make sure to add this to your theme's `functions.php` to handle pagination with pretty permalinks:
function fix_pagination($query) {
if (!is_admin() && $query->is_main_query() && $query->is_home()) {
$query->set('paged', get_query_var('paged'));
}
}
add_action('pre_get_posts', 'fix_pagination');
### Step 3: Ensure Your Permalink Structure is Set
– Go to **Settings** → **Permalinks** in the WordPress dashboard.
– Ensure that **Post name** or any other pretty permalink structure is enabled.
### Step 4: Using Pagination in a Custom Template
If you’re using this code in a custom page template, set it up like this:
/*
Template Name: Custom Post Listing with Pagination
*/
get_header();
?>
<div class="container">
<?php include locate_template('path/to/your-pagination-code.php'); ?>
</div>
<?php get_footer(); ?>
This approach gives you more control over how the posts are displayed and provides a user-friendly pagination system.
// Constructor
public function __construct() {
parent::__construct( [
'singular' => 'user', // Singular name of the item
'plural' => 'users', // Plural name of the item
'ajax' => false, // Whether this table supports ajax
] );
}
// Define the columns for the table
public function get_columns() {
// Return an array of columns with the column name as the key and label as the value
return [
'username' => 'Username',
'email' => 'Email',
'signup' => 'Sign Up Date',
'actions' => 'Actions',
];
}
// Prepare the items for the table
public function prepare_items() {
global $wpdb;
$per_page = 10; // Number of items per page
$current_page = $this->get_pagenum();
// Get the users with 'aiowps_account_status' set to 'lock'
$args = [
'meta_key' => 'aiowps_account_status',
'meta_value' => 'pending',
'fields' => ['ID', 'user_login','user_email','user_registered'],
'number' => $per_page,
'offset' => ( $current_page – 1 ) * $per_page
];
$users = get_posts($args);
$total_users = count(get_users([
'meta_key' => 'aiowps_account_status',
'meta_value' => 'pending',
'fields' => ['ID']
]));
// Prepare the data (rows)
$data = [];
foreach ( $users as $user ) {
$data[] = [
'username' => $user->user_login,
'email' => $user->user_email,
'signup' => date('F j, Y at g:i a', strtotime($user->user_registered)),
'actions' => sprintf(
'Approve',
admin_url('admin.php?action=userwp_approve_user&user_id=' . $user->ID)
)
];
}
$this->set_pagination_args([
'total_items' => $total_users, // Total number of items
'per_page' => $per_page, // Number of items per page
'total_pages' => ceil($total_users / $per_page) // Total number of pages
]);
// Set the data for the table
$this->items = $data;
// Getting column names
$columns = $this->get_columns();
// Setting columns to hide
$hidden = $this->get_hidden_columns();
// print_r($columns);
// Setting column names to sort by
$sortable = $this->get_sortable_columns();
// Showing columns in table
$this->_column_headers = array($columns,$hidden,$sortable);
// Pagination
}
public function get_hidden_columns()
{
return array('id');
}
// Add column names that has sortable functionality
public function get_sortable_columns()
{
return array(
);
}
public function column_default($item, $column_name)
{
switch ($column_name) {
case 'username':
return $item['username'];
break;
case 'email':
return $item['email'];
break;
case 'signup':
return $item['signup'];
break;
case 'actions':
return $item['actions'];
break;
default:
return isset($item[$column_name]) ? $item[$column_name] : '';
}
}
// Column output
public function column_username( $item ) {
return esc_html( $item['username'] );
}
public function column_actions( $item ) {
return $item['actions'];
}
}
replace get_users to Wp_query in above and post_type='app'
### Updated Code:
class Pending_User_Approval_List extends WP_List_Table {
// Constructor
public function __construct() {
parent::__construct([
'singular' => 'user', // Singular name of the item
'plural' => 'users', // Plural name of the item
'ajax' => false, // Whether this table supports ajax
]);
}
// Define the columns for the table
public function get_columns() {
return [
'username' => 'Username',
'email' => 'Email',
'signup' => 'Sign Up Date',
'actions' => 'Actions',
];
}
// Prepare the items for the table
public function prepare_items() {
global $wpdb;
$per_page = 10; // Number of items per page
$current_page = $this->get_pagenum();
// Set up WP_Query arguments to get users with 'aiowps_account_status' set to 'pending'
$args = [
'post_type' => 'app',
'meta_key' => 'aiowps_account_status',
'meta_value' => 'pending',
'posts_per_page' => $per_page,
'paged' => $current_page,
'fields' => 'all',
];
// Use WP_Query to get the posts
$query = new WP_Query($args);
$users = $query->posts; // Get the posts
$total_users = $query->found_posts; // Get total users count
// Prepare the data (rows)
$data = [];
foreach ($users as $user) {
$data[] = [
'username' => $user->post_title, // Assuming post title is the username
'email' => get_post_meta($user->ID, 'user_email', true), // Assuming custom meta for email
'signup' => date('F j, Y at g:i a', strtotime($user->post_date)),
'actions' => sprintf(
'<a href="%s">Approve</a>',
admin_url('admin.php?action=userwp_approve_user&user_id=' . $user->ID)
),
];
}
// Set pagination arguments
$this->set_pagination_args([
'total_items' => $total_users, // Total number of items
'per_page' => $per_page, // Number of items per page
'total_pages' => ceil($total_users / $per_page) // Total number of pages
]);
// Set the data for the table
$this->items = $data;
// Getting column names
$columns = $this->get_columns();
// Setting columns to hide
$hidden = $this->get_hidden_columns();
// Setting column names to sort by
$sortable = $this->get_sortable_columns();
// Showing columns in table
$this->_column_headers = [$columns, $hidden, $sortable];
}
public function get_hidden_columns() {
return ['id'];
}
public function get_sortable_columns() {
return [];
}
public function column_default($item, $column_name) {
switch ($column_name) {
case 'username':
return $item['username'];
case 'email':
return $item['email'];
case 'signup':
return $item['signup'];
case 'actions':
return $item['actions'];
default:
return isset($item[$column_name]) ? $item[$column_name] : '';
}
}
// Column output
public function column_username($item) {
return esc_html($item['username']);
}
public function column_actions($item) {
return $item['actions'];
}
}
### Explanation of Changes:
1. **Replaced `get_users()` with `WP_Query`**:
– Updated the `$args` array to match `WP_Query` format.
– Used `'post_type' => 'app'` to fetch posts with the custom post type `'app'`.
– Added `'fields' => 'all'` to get the full post object.
2. **Pagination**:
– Used `$query->found_posts` to get the total count of posts.
– Updated the pagination logic to use `$query->max_num_pages`.
3. **Data Handling**:
– Updated data preparation to use post object properties like `$user->post_title` and `$user->post_date`.
– Used `get_post_meta()` to retrieve custom fields like `'user_email'`.
### Note:
Ensure that:
– The custom post type `'app'` exists.
– The meta key `'aiowps_account_status'` is used for the posts.
– The email data is stored in a custom meta field named `'user_email'`.
This code should now fetch data using `WP_Query` and display it with pagination.