Wordpress CPT Archive Pagination - Displays too many pages - php

I've been trying to figure out why my custom post type archive is displaying too many pages in the pagination.
My pagination is being displayed by FacetWP using the following code:
<?php echo facetwp_display('pager'); ?>
I've tried customizing how it displays, but each time it still continues to show too many pages. However, when I select a filter, then the pages will be correct.
Is there a way to make it so that it will automatically display the number of pages for each custom post type archive?
EDIT: Since I’m not an advanced php user myself, I've only tried the customization code provided by FacetWP's documentation.
$params = array(
'page' => 1,
'per_page' => 10,
'total_rows' => 205,
'total_pages' => 21 );
And
add_filter( 'facetwp_pager_html', function( $output, $params ) {
$output = '';
if ( 1 < $params['total_pages'] ) {
for ( $i = 1; $i <= $params['total_pages']; $i++ ) {
$is_curr = ( $i === $params['page'] ) ? ' active' : '';
$output .= '<a class="facetwp-page' . $is_curr . '" data-page="' . $i . '">' . $i . '</a>';
}
}
return $output; }, 10, 2 );
And
function my_facetwp_pager_html( $output, $params ) {
$output = '';
$page = $params['page'];
$total_pages = $params['total_pages'];
if ( $page > 1 ) {
$output .= '<a class="facetwp-page" data-page="' . ($page - 1) . '">Previous</a>';
}
if ( $page < $total_pages && $total_pages > 1 ) {
$output .= '<a class="facetwp-page" data-page="' . ($page + 1) . '">Next</a>';
}
return $output; } add_filter( 'facetwp_pager_html', 'my_facetwp_pager_html', 10, 2 );
Sorry if any of that code is messy, let me know if I need to repost for clarification. Thanks in advance for any help!

Related

Wordpress paginate_links function: How do i ensure the page number is not less than 1 and not greater than last

I have a $wpdb query that selects all rows from MySQL table written in a custom php file. The query returns 2122 results. I have set the the code to output 20 rows per page which means i have a total of 107 pages.
The last page url renders like so:
localhost/index.php/publications/?cpage=107
My problem is that when i insert an argument like 108 e.g.,localhost/index.php/publications/?cpage=108 (which is greater than last page) or the argument 0(which is less than 1) e.g., localhost/index.php/publications/?cpage=0 in the the link, wordpress goes ahead and renders a blank page. How does wordpress validate pagination urls? What should i change to ensure that when a user enters an argument less than 1 they are redirected to page 1? Likewise, how do i ensure that if a user inserts a page number greater than the last page in the url wordpress redirects to the lastpage?
Here is my code:
<?php
$totalresults = $wpdb->get_var("SELECT COUNT(*) FROM ".$wpdb->prefix."refs1 ");
$limit = 20;
$currentpage = isset($_GET['cpage']) ? (int)$_GET['cpage'] : 1;
$offset = ($currentpage * $limit) - $limit;
$numbering = ((($currentpage*$limit)-$limit)+20);
$lastpage = ceil($totalresults / $limit);
if($lastpage <1){
$lastpage = 1;
}
//
$pagenumber = 1;
//
/**Here is my attempt to ensure users are redirected to lastpage/first
page if they enter wrong arguments in the url **/
if(isset($_GET['cpage'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['cpage']);
}
if ($pagenum < 1){
$pagenum = 1;
} else if ($pagenum > $lastpage){
echo "past lastpage";
$pagenum = $lastpage;
}
$get = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."refs1 " . "LIMIT $offset, $limit");
$i = $offset+1;
foreach ($get as $result){
$citation = $result->citation;
$cit1 = strtok($citation, ".");
$cit2 = substr($citation, strpos($citation, ".") + 1);
//echo $cit2 . "<br>";
echo "<p>" . $i++ . ". " . "<a href = '#'>" . $result->title . "." . "</a>". "<br>" . $result->authors . "<br>" . "<u>" . $cit1 . "." . "</u>" . $cit2 . "<br>" ;
}
//pagination_pages();
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'total' => ceil($totalresults / $limit),
'current' => $pagenum
));

Set up a number of categories to display on a page

I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages
$categories = get_categories();
foreach($categories as $category) {
echo '<div class="col-md-4"><a href="' .
get_category_link($category->term_id) . '">' . $category->name
. '</a></div>';
}?>
this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations
$page=$_GET['page_number'];
$categories = get_categories();
$data=array_chunk($categories ,3);
$paginations=count($data); // use loop for paginations in html page
foreach($data[$page] as $category) {
echo '<div class="col-md-4"><a href="' .
get_category_link($category->term_id) . '">' . $category->name
. '</a></div>';
}
as per my comments above. the code example I can give you is as follows
for($i = 0; $i <= count($categories); $i++) {
/*
Pagination purposes this is how you can format data to an object
base.
*/
if($i % 3 = 0) {
// add to an array
}
}
for ($i = 0; $i <= 3; $i++) {
// echo categories HTML but $categories[$i] instead
}
though let it be known that this wont fully work as you would think etc... etc... I cant explain the modulus operator in depth as I cant think of an easy way without you trying to learn it so you can understand it well.
this way you are only getting 3
$startCategory = 0;
for($i = $startCategory; $i <= count($categories); $i++) {
echo '<div class="col-md-4">' . $categories[$i]['name']. '</div>';
$startCategory++;
if($startCategory > (count($categories) -1)){
break;
}
//pass $startCategory to next page , next page
$startCategory = $_POST["startCategory"]; // by using post method
$startCategory = $_GET["startCategory"]; // by using get method
for($i = $startCategory; $i <= count($categories); $i++) {
echo '<div class="col-md-4"><a href="' .
get_category_link($categories[$i]['term_id']) . '">' . $categories[$i]['name']
. '</a></div>';
$startCategory++;
if($startCategory > (count($categories) -1)){
break;
}
}

How to use PHP pagination in array's

Since I am trying to learn more about PHP I would like to add Pagination to array's
I have a JSON output that I can read and echo via a foreach. But I am not able to show 10 or 20 records.
I have used the code from this page:
But I miss the place where I can store the echo for the array.
$persons = '[
{"FrstName":"Henry","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
{"FrstName":"Klaus","Middlename":"","LastName":"Mikaelson","Online":true,"DeptId":"2"},
{"FrstName":"Kylo","Middlename":"","LastName":"Ren","Online":false,"DeptId":"4"},
{"FrstName":"Stan","Middlename":"","LastName":"Lee","Online":false,"DeptId":"3"},
{"FrstName":"Kevin","Middlename":"","LastName":"McNally","Online":false,"DeptId":"3"},
{"FrstName":"Katherine","Middlename":"","LastName":"Pierce","Online":false,"DeptId":"2"},
{"FrstName":"Clint","Middlename":"","LastName":"Barton","Online":true,"DeptId":"3"},
{"FrstName":"Avery","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
{"FrstName":"Peter","Middlename":"","LastName":"Kap","Online":true,"DeptId":"2"},
{"FrstName":"Denzo","Middlename":"","LastName":"Falc","Online":false,"DeptId":"4"},
{"FrstName":"Eveline","Middlename":"","LastName":"Benzel","Online":false,"DeptId":"3"},
{"FrstName":"Bill","Middlename":"","LastName":"Libuz","Online":false,"DeptId":"3"},
{"FrstName":"April","Middlename":"","LastName":"Gonzo","Online":false,"DeptId":"2"},
{"FrstName":"Harry","Middlename":"","LastName":"Geraldson","Online":true,"DeptId":"3"},
{"FrstName":"Heraldson","Middlename":"","LastName":"McGree","Online":false,"DeptId":"3"}
{"FrstName":"Abraham","Middlename":"","LastName":"Retz","Online":true,"DeptId":"4"},
{"FrstName":"June","Middlename":"","LastName":"Pharee","Online":true,"DeptId":"2"},
{"FrstName":"Anthony","Middlename":"","LastName":"Gonzales","Online":false,"DeptId":"4"},
{"FrstName":"Billy","Middlename":"","LastName":"Scott","Online":false,"DeptId":"3"},
{"FrstName":"Anika","Middlename":"","LastName":"Rose","Online":false,"DeptId":"3"},
{"FrstName":"Kristen","Middlename":"","LastName":"Fontana","Online":false,"DeptId":"2"},
{"FrstName":"Olivia","Middlename":"","LastName":"Menzel","Online":true,"DeptId":"3"},
{"FrstName":"Mark","Middlename":"van","LastName":"Gad","Online":false,"DeptId":"3"}
{"FrstName":"Hope","Middlename":"van","LastName":"Dyne","Online":false,"DeptId":"3"}
]';
$page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$total = count( $persons ); //total items in array
$limit = 10; //per page
$totalPages = ceil( $total/ $limit ); //calculate total pages
$page = max($page, 1); //get 1 page when $_GET['page'] <= 0
$page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($page - 1) * $limit;
if( $offset < 0 ) $offset = 0;
$yourDataArray = array_slice( $persons, $offset, $limit );
$link = 'index.php?page=%d';
$pagerContainer = '<div style="width: 300px;">';
if( $totalPages != 0 )
{
if( $page == 1 )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( ' « prev page', $page - 1 );
}
$pagerContainer .= ' <span> page <strong>' . $page . '</strong> from ' . $totalPages . '</span>';
if( $page == $totalPages )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( ' next page » ', $page + 1 );
}
}
$pagerContainer .= '</div>';
echo $pagerContainer;
I would like to know how I can fix this to use pagination for my array.
You need to json_decode() your JSON first to access array methods (count(), array_slice()). Also, your JSON data was invalid, missing some commas, fixed that.
<?php
$persons = '[
{"FrstName":"Henry","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
{"FrstName":"Klaus","Middlename":"","LastName":"Mikaelson","Online":true,"DeptId":"2"},
{"FrstName":"Kylo","Middlename":"","LastName":"Ren","Online":false,"DeptId":"4"},
{"FrstName":"Stan","Middlename":"","LastName":"Lee","Online":false,"DeptId":"3"},
{"FrstName":"Kevin","Middlename":"","LastName":"McNally","Online":false,"DeptId":"3"},
{"FrstName":"Katherine","Middlename":"","LastName":"Pierce","Online":false,"DeptId":"2"},
{"FrstName":"Clint","Middlename":"","LastName":"Barton","Online":true,"DeptId":"3"},
{"FrstName":"Avery","Middlename":"","LastName":"Walton","Online":true,"DeptId":"4"},
{"FrstName":"Peter","Middlename":"","LastName":"Kap","Online":true,"DeptId":"2"},
{"FrstName":"Denzo","Middlename":"","LastName":"Falc","Online":false,"DeptId":"4"},
{"FrstName":"Eveline","Middlename":"","LastName":"Benzel","Online":false,"DeptId":"3"},
{"FrstName":"Bill","Middlename":"","LastName":"Libuz","Online":false,"DeptId":"3"},
{"FrstName":"April","Middlename":"","LastName":"Gonzo","Online":false,"DeptId":"2"},
{"FrstName":"Harry","Middlename":"","LastName":"Geraldson","Online":true,"DeptId":"3"},
{"FrstName":"Heraldson","Middlename":"","LastName":"McGree","Online":false,"DeptId":"3"},
{"FrstName":"Abraham","Middlename":"","LastName":"Retz","Online":true,"DeptId":"4"},
{"FrstName":"June","Middlename":"","LastName":"Pharee","Online":true,"DeptId":"2"},
{"FrstName":"Anthony","Middlename":"","LastName":"Gonzales","Online":false,"DeptId":"4"},
{"FrstName":"Billy","Middlename":"","LastName":"Scott","Online":false,"DeptId":"3"},
{"FrstName":"Anika","Middlename":"","LastName":"Rose","Online":false,"DeptId":"3"},
{"FrstName":"Kristen","Middlename":"","LastName":"Fontana","Online":false,"DeptId":"2"},
{"FrstName":"Olivia","Middlename":"","LastName":"Menzel","Online":true,"DeptId":"3"},
{"FrstName":"Mark","Middlename":"van","LastName":"Gad","Online":false,"DeptId":"3"},
{"FrstName":"Hope","Middlename":"van","LastName":"Dyne","Online":false,"DeptId":"3"}
]';
// Make the JSON an array, so count() and array_slice() work
$persons = json_decode($persons, true);
$page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$total = count( $persons ); //total items in array
// $limit = 10; //per page
// Set limit to 3 for testing:
$limit = 3;
$totalPages = ceil( $total/ $limit ); //calculate total pages
$page = max($page, 1); //get 1 page when $_GET['page'] <= 0
$page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
// Uncomment this for testing
// $page = 2;
$offset = ($page - 1) * $limit;
if( $offset < 0 ) $offset = 0;
$yourDataArray = array_slice( $persons, $offset, $limit );
$link = 'index.php?page=%d';
$pagerContainer = '<div style="width: 300px;">';
if( $totalPages != 0 )
{
if( $page == 1 )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( ' « prev page', $page - 1 );
}
$pagerContainer .= ' <span> page <strong>' . $page . '</strong> from ' . $totalPages . '</span>';
if( $page == $totalPages )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( ' next page » ', $page + 1 );
}
}
$pagerContainer .= '</div>';
echo $pagerContainer;
foreach($yourDataArray as $person) {
echo "\n";
echo "First name: " . $person['FrstName'];
echo " - Middle name: " . $person['Middlename'];
echo " - Last name: " . $person['LastName'];
echo " - Online: " . $person['Online'];
echo " - Dept: " . $person['DeptId'];
}
https://3v4l.org/8hR84

WordPress post ratings location change of showing

I am a new developer. This code has used form plugin for showing rating average and its working well. But its showing rating above of WP content. I want to show rating on my several specific location of blog page and single page. How can I do that?
add_filter( 'the_content', 'ci_comment_rating_display_average_rating' );
function ci_comment_rating_display_average_rating( ) {
global $post;
if ( false === ci_comment_rating_get_average_ratings( $post->ID ) ) {
return $content;
}
$stars = '';
$average = ci_comment_rating_get_average_ratings( $post->ID );
for ( $i = 1; $i <= $average + 1; $i++ ) {
$width = intval( $i - $average > 0 ? 20 - ( ( $i - $average ) * 20 ) : 20 );
if ( 0 === $width ) {
continue;
}
$stars .= '<span style="overflow:hidden; width:' . $width . 'px" class="dashicons dashicons-star-filled"></span>';
if ( $i - $average > 0 ) {
$stars .= '<span style="overflow:hidden; position:relative; left:-' . $width .'px;" class="dashicons dashicons-star-empty"></span>';
}
}
$custom_content = '<p class="average-rating">This post\'s average rating is:-- ' . $average .' ' . $stars .'</p>';
$custom_content .= $content;
return $custom_content;
}

Upgrading a PHP pagination function to run faster

I created a pagination for an website file last year, and I've never really had to use it again.
But now I'll need to use it in a bigger application, and I'm afraid it won't behave really good with a huge amount of mysql rows, I don't know.
I'll post an example bellow and I'll be greatful if someone could tell me if I really need to upgrade the code.
/* Connection file */
include( 'config.php' );
/* Get the amount of all rows */
$mqc = "SELECT COUNT(*) AS total FROM table";
$mqe = mysql_query( $mqc );
$mqn = mysql_fetch_array( $mqe );
$total = $mqn['total'];
/* Rows per page */
$perPage = 10;
/* Range for the pagination */
$range = 5;
/* Actual page */
$page = isset( $_GET['page'] ) &&
is_numeric( $_GET['page'] ) &&
!empty( $_GET['page'] ) ?
( (int)$_GET['page'] * $range ) : 0;
/* Query */
$mqc = "SELECT * FROM table
LIMIT " . $page . ", " . $perPage . " ";
$mqe = mysql_query( $mqc );
/* Show results */
while( $l = mysql_fetch_object( $mqe ) )
{
echo $l->id . ' - ' . $l->title . '<br />';
}
/* Function for pagination */
function pages( $total = false, $perPage = false, $page = false, $range = false )
{
/* Number of pages */
$totalPages = ( ceil( $total / $perPage ) ) - 1;
/* The range * 2 */
$range = $range;
/* The real param $_GET['page'] */
$realGetPage = !empty( $page ) ? ( $page / $range ) : 0;
/* Show the first page */
if($realGetPage >= 7)
{
echo ' 1 ... ';
}
/* Loop to create the range */
for($i = ( $realGetPage - $range ); $i < ( $range + $realGetPage ); $i++)
{
/* Check out if the value isn't outta range */
if( $i > 0 && $i < $totalPages )
{
/* Highlight the actual page */
if( ( $i - 1 ) == $realGetPage )
{
echo ' [ ' . $i . ' ] ';
}
else
{
echo ' ' . $i . ' ';
}
}
/* Store the number of the last page */
$lastPage = ( $i + 1 );
}
/* Hack to show 5678910 */
if( $lastPage < ( $range * 2 ) + 1 )
{
for( $j = $lastPage; $j <= ( $range * 2 ); $j++ )
{
if( ($j - 1) == $realGetPage )
{
echo ' [ ' . $j . ' ] ';
}
else
{
echo ' ' . $j . ' ';
}
}
}
/* Last page */
echo ' ... ' . $totalPages . ' ';
}
/* Show the pagination */
pages( $total, $perPage, $page, $range );
What do you think?
From the information you provided in your comment, the performance issues you might have will not come from your PHP script. If you do multiple INNER JOINS on huge tables, this is exactly what will affect your performance. Some important things to look for:
Tables indexes (if you use filters, for your joins if you don't join on primary keys)
Optimizing your table / queries to decrease the number of JOINs
If you expect a lot of traffic, consider using caching for your queries (memcached for instance)
As Phil mentionned, the ORDER BY must be used to render a predictable result and could slow down your queries if the tables are used. You could pre-render ordered table using a cron job
Consider using denormalization to reduce the number of JOINS
The main thing I see missing is an ORDER BY clause. Without this, your paged results are (potentially) unpredictable.
Add an ORDER BY clause and make sure you have appropriate database indexes in place on the sortable column(s).
I'd also recommend switching to a more up-to-date database connection library with prepared statements and bound parameters. Please see PDO.

Categories