adding Pagination to a shortcode
-
snippet of my functions.php file below
Outside of this shortcode, I have had no issues adding pagination.
Ive followed a few video tutorials that didn’t work at all, even went over my code to see how I can tweak it. I haven’t had any success. Note: the pagination code on the bottom is working for my other post pages that don’t use this shortcode.
preferably id like to add the same pagination code you see to work with the shortcode.
any input or a push in the right direction would be appreciated . thanks
/* ================================= shortcode Displays posts from specified categories on homepage ================================= */ add_filter( 'category_description', 'do_shortcode'); function wpb_postsbycategory() { // the query $the_query = new WP_Query( array( 'category_name' => 'pictures, stories', 'posts_per_page' => 10 ) ); // The Loop if ( $the_query->have_posts() ) { $string .= '<ul class="postsbycategory widget_recent_entries">'; while ( $the_query->have_posts() ) { $the_query->the_post(); if ( has_post_thumbnail() ) { $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() . '</a></li>'; $string .= '<li>';$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 500, 500) ) . '</a></li>'; } else { // if no featured image is found $string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>'; $string .= '<li> '. get_the_content() .'</li>'; } } } else { // no posts found } $string .= '</ul>'; return $string; /* Restore original Post Data */ wp_reset_postdata(); } // Add a shortcode add_shortcode('categoryposts', 'wpb_postsbycategory'); // Enable shortcodes in text widgets add_filter('widget_text', 'do_shortcode'); /* ================================= Pagination ================================= */ function pagination_bar() { global $wp_query; $total_pages = $wp_query->max_num_pages; if ($total_pages > 1){ $current_page = max(1, get_query_var('paged')); echo paginate_links(array( 'base' => get_pagenum_link(1) . '%_%', 'format' => '/page/%#%', 'current' => $current_page, 'total' => $total_pages, )); } }
-
What is your concept here? The comment above your code says this shortcode is for the home page. When you say “paginate”, we are really just reloading the same home page, except different posts are displayed, “page” by “page”, but always on the home page. Am I correct?
Anytime you have a custom query that needs to be paged through, you cannot rely on WP pagination functions. They work based on the main query, in this case the home page. It doesn’t even make sense to paginate a home page. The main query is for one page, there’s nothing to paginate through the main query.
You can still cause different posts to be displayed, but you should manage the pagination yourself. Do not try to use traditional pagination URLs like /my-posts/page/3/. WP will try to query for page 3 of your home page and the result will be nothing found. The page of the shortcode posts should be passed as an URL parameter, as in example.com/?my-posts=3.
Your pagination script can then get the value from $_GET[‘my-posts’]. Your query will need to utilize the ‘offset’ argument to manage which page of posts are being queried for. Calculate the offset by multiplying the posts per page by the requested page minus 1. For example, if page 4 is requested and there are 10 posts per page,
$offset = 10 * (4 - 1)so ‘offset’ => 30, Be sure the you are not on the last page before putting out a next page link. The total posts for your query is $the_query->found_posts.Be sure your pagination calculations occur before the call to wp_reset_postdata() or you will get improper results.
What is your concept here? The comment above your code says this shortcode is for the home page. When you say “paginate”, we are really just reloading the same home page, except different posts are displayed, “page” by “page”, but always on the home page. Am I correct?
Yes. example http://www.mypage.com/page/2 , http://www.mypage.com/page/3 etc
Anytime you have a custom query that needs to be paged through, you cannot rely on WP pagination functions. They work based on the main query, in this case the home page. It doesn’t even make sense to paginate a home page. The main query is for one page, there’s nothing to paginate through the main query.
Yes I totally understand it doesn’t make sense. The way my site is gonna be set up..i need my home page to have pagination of all posts from 4 different categories. Id also like to switch it up in the future where other pages will use the same short code.
thanks for a push in the right direction. however im afraid im confused on how to go about implementing what you just told me. haha. I wouldn’t no where to start making a shortcode to display posts and be paginated at the same time. lol
so basically I have to start from scratch. I need the latest posts from 4 categories to be displayed on my home page.
10 per page, and then paginated. I want everyone to be able to find a post that’s interesting instead of manually going to each category one at time to find something interesting.
From scratch, perhaps yes. But if I understand what you are trying to do correctly, there’s a relatively simple solution. The fact you were using a shortcode on the home page led me to assume you have setup your home page to be “static”. (Most static home pages I’ve seen are anything but static) Is there other significant main content on your home page? Not things in header, footer, sidebar, etc. I mean the main part of the page. Or is the shortcode output pretty much it?
If just the shortcode output, then switch your site back to showing the latest posts instead of a static front page. You can modify which posts are shown by hooking the “pre_get_posts” filter and altering query vars to suit. Do not alter anything unless $query->is_main_query() AND $query->is_home() are true for the passed query object. You can limit posts to those with any of 4 categories by setting the ‘category__in’ query var to an array of the 4 category IDs. Done this way, the normal pagination should work without any need to fuss with it.
If you do have other content that should appear in the main content, this can still be accommodated despite a latest posts configuration. Add an area to the index.php theme template that outputs the desired content only when is_front_page() is true.
In case you’ve not done so, unless you’ve built your own theme, you should create a child theme to contain all of your custom work. Otherwise your work will be lost when a theme is updated.
In case you’ve not done so, unless you’ve built your own theme, you should create a child theme to contain all of your custom work. Otherwise your work will be lost when a theme is updated.
Yes I have other content. Under the main header nav I have 4 categories showing the latest featured image from each category in a row. I have built it from scratch. well using tutorials etc. However Im afraid my main problem here is understanding programming again, and foremost. learning wordpress functions and what they do. I might need to pick up a good book. I used to code basic, VB, vb-scriot, html when I was 14-16 using anglefire. but..i haven’t done anything since. now its over 20 years later. lmao.
-
This reply was modified 9 years, 1 month ago by
juicyjuke.
😀 That sounds familiar. I was in the same position about 5 years ago, except I was older when I stop coding prior to that. Now I find myself a WP expert of a sort. I knew absolutely zip of PHP, though I’ve had prior experience in a number of languages. I picked up the essentials pretty quickly. I still have to look up a lot of things, my memory sucks.
You must already have the code to get the images and output them. Break it out into a function. On index.php of your theme, conditionally call the function when is_front_page() is true. If you don’t want the images on subsequent pages, get the ‘paged’ query var from the global $wp_query and only call the image function if it’s not set or is 1. Not too different than VB, except for different syntax 😉
This way index.php can still be used as a general template, but you get special home page output as well once you go back to showing latest posts on the front page as I described previously. Then the post listing works conventionally and pagination works without any special handling.
makes all sense what you said. its just learning how to do it again. I started following a 24 part build your theme from scratch tutorial, and after the 7th lesson I got what I needed and went on from there. ive got work in between. what I need is a good book to knock it all into my head again. like even VB I forgot. at least I understand what things do. any suggestions on what to read in order to implement what you said? or maybe even send you a zip of all my code? id be willing to compensate for your time. email? I don’t have a whole bunch of code. very simple. well for someone like you at least.
its hard to explain how I know what I know already without understanding exactly how to do what you said. I find myself doing some things that require good experience yet not being able to do things that a beginner can do.
make sense?I’m unable to recommend any books on programming. I’ve never been able to learn that way. I’ve always learned by doing. It’s struggle at first, taking forever to accomplish the simplest of tasks. It eventually starts to make sense. Struggling through a real project has always worked better for me than following along with some arbitrary tutorial. I think it’s because I am forced to think for myself how to accomplish a task. Coding is not really about writing code (!), it is about deciding how to manipulate input to get desired output. Writing code is merely documenting in a formal, structured manner what process you decided upon. Everyone learns differently, you need to do what works for you.
You already understand how strictly logical computers are, and what sort of logic structures are available that are common to any computer language, even if the syntax is different. It all can essentially be reduced to if this, do that, otherwise do the other. Sure, you don’t know what functions are available, and you may end up doing something the hard way because you are unaware that there’s a function for that. That’s OK, you still solved a problem. You’ll eventually pickup what you really need to know. If you do get stuck, you can likely search for an answer, or ask here or in any other coding forum.
I appreciate your willingness to compensate for my time, however it is strictly against the forum guidelines here to offer or accept any kind of compensation. By simply offering, you can end up being approached by others who are willing to ignore the guidelines here for pay. You must ignore such offers. You do not know who these people are and what their true motives may be. While most here are well intentioned, that is not always the case. If you really need experienced help and are willing to pay, you can find competent help at jobs.wordpress.net This not some veiled scheme for us to communicate outside this forum, I do not monitor that site.
If you break this down into small, discrete steps and just focus on the immediate task, I believe you can struggle through this with some guidance. Before starting on that though, if you intend to improve your PHP skills, you will be well served to setup up a localhost server environment if you have not already done so. Setup a WP installation for testing and learning, on which you can follow tutorials and such without impacting your real site, of which it is also useful to have a localhost version. WP installs do not take up much space unless a site has a huge amount of content. Be sure the wp-config.php of your test install has WP_DEBUG defined as true.
I know you have your own theme, but to avoid possible conflicts, your test installation should use the twentysixteen theme (or in general one theme earlier than the latest default theme) and no plugins. Setup a child theme of twentysixteen to contain your work. If you will be developing a plugin, that should be the only active plugin. Create a test template based on twentysixteen’s page.php copied to the child’s folder. Replace the header comment with the one required for custom global page templates. For example:
/* Template Name: Foobar */Also remove the loop and the get_sidebar() calls. You’ll be placing test code where the loop was. Create a new WP page based on this template. To test any code you enter on the template, simply request the WP page. Or make that page the site’s static front page and simply enter the localhost IP to reach it.Your test site will need some content beyond Hello World! You could clone your current site’s DB if it’s not too huge. Or make several posts with only lorem ipsum content. At least one in each of the 4 categories, with featured images. It doesn’t matter what the images are, but it may help if they relate to the category of the post.
Then as I suggested, extract the portion of your shortcode handler responsible for getting the latest image in each of the 4 categories and outputting the img tags. Make that code into a function on functions.php. Add a call to that function on your test page template. Load the test page and see what happens. The appearance is not important, all you are after is for the output to be proper HTML that matches your current site’s front page. Maybe the images are stacked vertically instead of 4 across. That’s OK, that is a CSS issue which can be addressed later.
If you have trouble determining what portion to extract, post your shortcode handler at pastebin.com and provide the link here. I’ll take a look and advise. Once you get this part completed, the remainder will fall into place quite quickly.
Yes ok. Turn it into a function then call that function my desired page/s php file. Ok that makes sense now.
Also …
Be sure the wp-config.php of your test install has WP_DEBUG defined as true.
I know you have your own theme, but to avoid possible conflicts, your test installation should use the twentysixteen theme (or in general one theme earlier than the latest default theme) and no plugins. Setup a child theme of twentysixteen
Ok I have done most of this . WP debug to see if it’s true however I have not. I have not used twenty 16 as a test. Will underscores be just as good to test?
Also I may have not explained. Somewhere in the middle of my theme creating I added Bootstrap . Personally that might of been a mistake as it just adds for things for me to know lol
I strongly advocate twentysixteen for now, and generally one theme back from the latest. This is the “just right” default theme, not too old, not too new. The reason for WP default themes is they are known to not cause any conflicts with core whatsoever. If any other code should conflict with a default theme, by definition the other code is causing a conflict, not the default theme or core. We are establishing a baseline “known good” configuration in which any other code must work correctly.
While I’m pretty confident that underscore would be fine, it’s not a default theme and if your test code conflicts with it, we cannot say with certainty if it’s your code at fault or underscore. This is strictly for testing new code. No one but you will be looking at it. It doesn’t matter what the site looks like, only that no errors are generated.
That is not to say you would not swap in a theme you are developing. That is fine, that is the expectation. But if you should encounter a mysterious problem, you should swap back to twentysixteen to analyze the problematic code snippet. If it works correctly under twentysixteen, our known good configuration, then there is something about your theme that needs to be identified and corrected.
It’s not necessary to religiously only develop in the baseline configuration. But if you should encounter a mysterious situation where something does not work with no apparent explanation, you will want to be able to quickly revert to baseline to confirm there is not some odd conflict with your current non-baseline setup.
ok check it out.
Pagination works!!
One thing id like to know however. Is this within the rules of wordpress? Like. is think ok for wordpress site?
add_filter( 'category_description', 'do_shortcode'); function wpb_postsbycategory($atts) { extract( shortcode_atts( array( 'expand' => '', ), $atts) ); global $paged; if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $posts_per_page = 10; $settings = array( 'showposts' => $posts_per_page, 'post_type' => 'post', 'category_name' => 'crazy-humorous-pictures, strange-news-stories, crazy-humorous-videos, crazy-funny-memes', 'orderby' => 'menu_order', 'order' => 'DESC', 'paged' => $paged ); $post_query = new WP_Query( $settings ); $total_found_posts = $post_query->found_posts; $total_page = ceil($total_found_posts / $posts_per_page); $list = '<ul class="postsbycategory widget_recent_entries">'; while($post_query->have_posts()) : $post_query->the_post(); if ( has_post_thumbnail() ) { $list .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() . '</a></li>'; $list .= '<li>'; $list .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 500, 500) ) . '</a></li>'; } else { // if no featured image is found $list .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>'; $list .= '<li> '. get_the_content() .'</li>'; } endwhile; $list.= '</ul>'; if(function_exists('wp_pagenavi')) { $list .='<div class="page-navigation">'.wp_pagenavi(array('query' => $post_query, 'echo' => false)).'</div>'; } else { $list.=' <span class="prev-posts-links">'.get_previous_posts_link('<< Previous ').'</span> <span class="next-posts-links">'.get_next_posts_link(' Next >>', $total_page).'</span> '; } return $list; } // Add a shortcode add_shortcode('categoryposts', 'wpb_postsbycategory'); // Enable shortcodes in text widgets add_filter('widget_text', 'do_shortcode');Awesome! It works the way it’s supposed to 😀
Is your code snippet OK in what context? On one hand, it’s your site, you may do what you like (as long as it’s legal). General WP coding guidelines? AFAICT, I don’t see any issues. Acceptable for inclusion in the WP theme repository? I don’t know. While there are basic guidelines, which basically say don’t be evil, there are more concerns of the review committee of which I’ve little knowledge of.
If you have a specific question about theme review criteria, you could ask the team on their Slack channel #themereview. They will not look at code there, but they ought to be able to answer something like “Is it OK if my theme adds shortcode support to the default text widget?” (or whatever your specific concern is)
Ok great. I will seek them out. Thanks for the advice.
What I meant? Ok as in. Does the shortcode I created do things how WordPress normally does them. Using the proper functions etc etc.
Oh, I see. Yes, looks good. Nice work!
-
This reply was modified 9 years, 1 month ago by
The topic ‘adding Pagination to a shortcode’ is closed to new replies.