Part 31 - WordPress Theme Development - Ajax Infinite Scroll - PART 1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys Alex here thank you for checking this video and welcome to the episode number 31 of the series of tutorial on how to build a prima theme for WordPress welcome again in this tutorial we're going to take a look on how to create an infinite loading option or an a synchronous loading option for our blog loop so right now or our blog posts are being printed on the front page because if we access our administration panel in the settings reading we have specified that we want to display 10 blog posts per page at most in our front index page so right now we have like 7 or 8 posts so everything fits in the first page but if we downsize this like we reduce this number to maybe 4 posts per page we saved changes and we update we refresh the page of course only 4 posts are gonna be displayed in the front page and because we did encode we didn't specify any source of pagination there's no way to access other post the previously published post the thing that I want to do in this sunset theme I don't want to create a custom or standard pagination where you have like go to page 2 or go to older blog post something like that we have in the standard WordPress themes but I want to create a button here to load more so dynamically load and append previously published blog posts underneath this last blog post that has been printed so let's take a look on how to do it first of all let's access our code editor and let's go inside our index dot PHP where are we printing that is like the blog loop page the first page where we printing everything and inside the blog logo right outside blog loop we have to create a button that it's gonna give the users the ability to click and load more posts so let's create another container that's out this one called of course this class container and I'm not using the same container of this one where the blog loop is for a really specific reason that I'm going to explain you later but here let's use container and let's use just like text center to central line is definitely it's used the standard bootstrap attribute bootstrap classes to style a button so I want a class of button and then button LG to specify large and then I want to button default I don't want any type of style and let's close this one let's create just simple load more and here we can specify our custom icon that we created so let's use span class sunset - sunset I don't remember the name of my custom icon so let's access the sass file where we have our base and fun icon and we have sunset loading let's close the span tag let's save it let's go back in our front-end let's refresh if we scroll down now we have this load more button with the sunset icon that is not actually working oops I forgot to sunset I can specify the actual class so let's refresh okay now it's working let's create just like to be better visually better we didn't create the filter yet but let's create a little bit of padding bottom padding space to have a little bit of padding and a little bit of breathing room for our footer so let's access our footer section and let's create a simple html5 footer class sunset - footer is his the footer let's go just text center so it's going to be center-aligned let's copy this new class that we just created here let's access our sensor dot s CSS let's scroll down at the bottom and let's create a new section here by copying this comment let's create an extra space and let's call it just footer section and then sunsets footer is gonna be for now I want to just a background color off like dark grey three to three then I want to give it a padding of 20 pixel top the bottom but not left and right and I want to give it a margin top off 40 pixel and of course I'm gonna have another declaration and display block just in case save it let's go back in our front-end let's refresh and now we have a little bit of more breathing room here this is our footer this a step further here the text just completely disappears but we don't care right now we created just the footer to have a little bit more space a little bit more reading room so now we have to add an action a JavaScript action to this button do you recognize when a user clicks on the button and to load the current status of the post so first of all we have to remember that to do on Ajax loading like a dynamic dynamic loading of new posts we need to do two different type of codes first we need a JavaScript code to endl the user action and then we need a PHP code a function to handle the loading of the blog post and the sending back the result of this loading to D Ajax function that is going to take care of printing everything on the front end so probably is gonna be a little bit confusing a little bit complicated but I'm gonna split this tutorial in two parts so I can deeply explain everything and I can guide you through this process of creating these a synchronous Ajax loading and it's not going to be confusing probably at the end of this first part is going to be like left half through is not going to be fully complete but we're gonna totally tackle all the remaining stuff in part two so let's keep going let's take care of the first thing first of all let's go back in our index dot PHP and we have to specify a bunch of html5 data attribute to this button because we have to send a bunch of information to our JavaScript function in order to have a proper loading so first of all I want to specify a data page that it's going to be the starting value is going to be page 0 so every time a load I load new posts I will dynamically update this number to reflect the page where we are currently so right now actually it's not zero because WordPress starts from page one so after a click I have to update this to page two and basically showing that to the JavaScript function we are watching page two so now you have to load page three and so on so on so for now we just need this data attribute value let's go back in our file tree and let's access the sunset dot J's file let's create a little bit of space let's put a comment here and call it a Jax functions and it's our coding a little bit of magic so first of all we have a super simple jQuery callback to detect the click of an element so in this case is document dot on open the brackets and let's right click as a function that we have to detect and we have to recognize comma open single quotes here we have to specify the class of the button or whatever element we want to recognize when the click happens so we have to specify a custom cause here and I know this sometimes developers used to use the standard class like for example if this button is side with button default they use button default or they use button as a class but I always suggest not use a class for a jQuery or a JavaScript callback function that it's associated to an actual style so always create a unique class that it's only only used for JavaScript and not for CSS or Sasso for styling so create a class only for a JavaScript function this will give you the ability to reuse the same class in other places without carry on also the entire CSS style that could be kind of annoying so let's call this class simply sunset - load - more that's pretty straightforward right so let's copy this custom class let's paste it here comma let's create function open brackets curly brackets and inside the curly brackets let's put a semicolon at the end of this entire function so now inside here we have to collect a bunch of information before kollene awara Ajax function so first we have to grab the current page of our blog loop so let's just write a bar to specify that we want to create a new variable in JavaScript and let's call this variable page that is going to be equal to dollar open these simple brackets this that in this case days is going to refer to the sunset load more and let's scroll this element is HTML element to find the data that we specified before and the data is page so if we simply console.log this page variable we just created maybe it's page let's refresh here let's open the console and let's go inside the console here we have everything activity so we're gonna have jQuery triggering so if we click load more we're gonna have a trigger of 1 inside the console because is the same information is the same element that we have inside the data page so these javascript is jQuery data function will access whatever custom information we specified here that it at it's attached to a data HTML attribute so if you specified - sunset you have to search for a data sunset in this case we're using data page that it's equal to one so we have to specify dot data and inside the brackets and single quotes the name of the html5 attribute data that we specify in this case page so let's keep going now another really important information that we need it is the Ajax URL so WordPress by default comes with an ajax URL that you can use to check where is this ajax URL let's go back a little bit inside e our default folder of our entire theme so in the sunset folder in my case where i have installed the entire wordpress installation if we go inside the WP admin folder we open the folder inside here as a second file we're going to have the admin - ajax dot PHP this is the file that if we access we probably won't recognize everything and it's kind of confusing it's kind of small but we don't have to worry about this file the only thing that we have to worry about is to point where this file is actually is so when we create a javascript function to call an ajax function we have to point the URL to this file to retract this file that could be tricky sometimes because we don't really know the name of the URL of the website that it's using our theme so we have to create a custom function to get that specific URL and WordPress comes with a custom function like that so let's access back the index dot PHP and let's create another html5 data attribute called data URL and equal inside the double quotes let's open the PHP tags and let's echo a function called admin underscore URL open the simple brackets and inside a single quote we have to specify which file in the admin folder we want to refer to we want to retry the URL in our case is the file admin - Ajax dot PHP the file that we saw before semicolon at the end let's save it let's refresh our front-end let's check the button in here inside the data URL we have these HTTP local sunset com that it's my actual URL and then we have the URL pointing to the file that we need so now we have this dynamic URL of course we could have simply because we actually know where this file is we could have simply manually write the entire address inside here or directly inside the JavaScript function but it's better not because if we decide to sell or to release this theme for free to be downloaded to be used we need a dynamic system of grabbing the current URL because we don't know what the URL of the website is going to be so this system is pretty good we have this URL and it's going to dynamically update itself if the website name changes or the URL changes so now we have these other data attribute that we have to retrieve and let's do it in the same way so let's duplicate this entire row let's copy data URL or to be more accurate let's use the ajax URL that is the variable that we need to point our javascript function to and in this case data it's of course URL let's save it now we can finally create our ajax call our Ajax function to call this specific URL so to create an ajax function we have to simply use the dollar sign because we define the dollar sign inside our function initially or if you want you can also write jquery if you don't want to use the dollar sign but because we specify the dollar sign as now holder of the jquery call function we can use the dollar sign so dollar dot Ajax and inside here let's open the simple bracket and then the curly brackets inside and let's open this section of course put a semicolon at the end as usual so we are not going to trigger any error so here first of all we have to specify the first value that is the URL where we wanna point is Ajax this a synchronous dynamic call - and of course the first value is called URL space column is not equal its column in here we have to specify the ajax URL that we want to point and we have this variable so just paste ajax URL comma here we have to specify another value that is the page value but the Ajax function here doesn't have a default page type of data that we can pass so it's if we use a page and then call on page this is going to trigger our error because Ajax doesn't recognize this page variable so we have to send this data inside wrapper inside a container a package container of Ajax to send custom data and create whatever we want so first we have to call data column and inside here let's open the curly brackets again so basically these data is a sort of array that contains all our custom data that we can write and send to the Ajax function the first parameter is of course like what's doing before page now we are safe to write a custom value that we want so page it's equal page because that's the name of the variable that could be confusing but it's not it's easier maybe to remember the second variable that I want to pass in this data is the actual action because we are sending this JavaScript to a PHP file and the PHP file in order to be properly triggered needs an action to trigger a specific function so the action has to be pretty much identical to the function that we want to call so in this case let's call sunset underscore lured underscore more that's it come up let's create a little bit of space here so it's going to be particularly on line to your screen after the comma inside er still inside the Ajax function we have two options to return an error or a success so if we write error this function this section this specific section is going to be trigger if these initial part the ajax URL and the sending data to the specific URL is triggering an error so we can write function brackets curly brackets let's go back here and then comma we can specify another status that we're going to fill up later of course it's going to call success so we have these two type of status and we can write of course the function again to specify whatever we want so the ajax comes by default we'd an error callback and a success callback and ajax is pretty smart to recognize the output whatever output is being returned from PHP to automatically trigger an error or a success and of course we PHP we can force the triggering on an error on our success bus if something goes wrong we can print response to bring the response inside the error callback automatically Ajax puts the error the actual response so let's call this variable response we don't have to define this variable because automatically HS is gonna inject this response variable with whatever response we're going to have from the function so we can simply console.log the response you could put and alert if you want but console.log is more subtle is just going to be print inside your console is not going to stop it's not going to give the user trigger any error that he can see so it's more like for a developer point of view if we have the success instead we can use the same variable response but in this case if we have success the response is gonna carry all the data there we are grabbing with the PHP function in our case the data are the new posts that we decide to load so we just simply need to append whatever information inside here so all the posts inside our container so let's call this dollar open bracket and we have to specify a class container where we wanna pend all our data to do that let's create a custom class inside this container to have a place to pray into all our posts and in this case the custom class is called Sunset - posts - container houses container so that's why I created two different containers and I'm not having these load more button inside the container because now that with JavaScript I'm appending new information to this container the load button would be before the new posts and I don't want that I wanted load button all week constantly at the bottom and not in between some sort of post loop so just it's better like that you will see if you try to put the button inside you will notice that after you append something it's not gonna be like the here key is not going to be good so let's keep it separated let's save these let's use this new class that we create it's called sunset posts container and let's use a jquery function simply called append to append whatever type of data so the append is gonna print whatever information we wanna pass here in this position append here because it's going to pen whatever information one just right before the closing tag of the container the element that we specify and of course we have to append just one variable that we have all in our case is the response variable that it's carrying all the blog posts that we have inside let's save it for now let's leave it like that this is a pretty barebone Ajax function that we can customize a lot but we're gonna see it in maybe in the next lesson now we have to create the PHP function so let's access back our file tree inside the Inc folder let's create a new file called Ajax PHP and we're creating a new file to keep everything separate especially Ajax functions in PHP tends to be tend to be as kind of big and kind of convoluted or complicated kind of like extend they kind of like a lot of rows a lot of declarations so it's always better to maintain your installation as clean as possible and not like having headaches if you have to retrieve your Ajax functions inside the mess of other files so inside Ajax function we can keep everything more organized of course let's copy the initial part of this section here let's close the footer we don't need CSS anymore not even the phone icon let's open the Ajax let's paste here and that's cold this any Jaxx functions any air we have to create a two actions Oh first of all let's include his new vial inside the functions dot PHP with a gat template directory otherwise it won't work so let's call it just include Ajax dot PHP we're good to go here we have to create you actions and a function so our function is going to be called exactly like the action we specify in the JavaScript Ajax function so sunset load more we want to keep everything consistent everything easy to remember we don't have to specify any variable or any attribute so we can open this function safely inside here we can have all our load more posts that we're gonna see later but before doing that we have to hook this stuff we have to hook these Ajax call to this function so if you remember now we are pointing this Ajax call to the ajax URL that is the admin - ajax dot PHP file we are not pointing this to the Ajax dot PHP custom file that we created so in order to hook this call to our custom file and in particular to our custom function we have to use a couple of of WordPress so first let's call ad underscore action let's open the simple bracket and the first declaration is called WP underscore Ajax underscore no Prayuth for no privileges underscore and then the function that we want to call so sunset load more and then as a second parameter after the comma again single quote again the name of the function so with this action we are saying to WordPress that we have an ajax call with no privileges so even a user that is not logged can call this sunset load more that it's equal to this custom function that we created we have to duplicate this action again and write the exact same text basically but removing the no privileges in order to activate this action this WP Ajax function also for a locked user if you want it this is a like a sort of security safety procedure of WordPress if you want this loading more available only for administrator or logged in user so not for non logged in user you can just simply comment or remove the no privilege action and leave this the standard WPI Ajax by default this will allow only logged user to use this specific function but we want to give the ability to use this function to everyone so we have to specify both the standard and the no privileges so always remember everything is connected we underscores also your function name is connected we underscore and then repeat your function name here and now here we can collect a little bit of information and actually grab all the information that our Ajax function is sending so because we are using the Ajax this by default this function is sending a post type of sending if we want to be more precise and a I'd mistake we can specify another building value of variable of Ajax to specify the type then in this case the type has to be post we want to be post of course and put a comma so the post type is the one that you see in a form if we had a form written here for example form you can specify a method that can be just get or post so the post method is a method that passes all the variables hidden inside the reload of the page or in our case inside the synchronous reloaded these variables are not getting printed anywhere the get method is something that prints the variables inside the URL so you will see the variables inside the URL and the gap method is really not safe and it's not really recommended to use but by default a form has always a post method and this method is the same thing that we're specifying here in the Ajax function so the type it's actually the method and in this case we are using post because we are using post so we're simulating the form post method we can retrieve all the information that we sent in our case we send the page and the action but we just really need the page with a simple dollar post PHP object so let's call this page that is the actual name of the WordPress query that we're going to see in a bit it's going to be equal to dollar under core post open the square brackets and inside here we have to specify the value that we want to retrieve and we call this value simply page so we have to specify page so now potentially this function is grabbing the current page of our post to check we could simply echo the page and the page variable and of course this will appear in the front end because we're printing it we are opinionated container before concluding the function though always remember that aji an AJAX function of wordpress always always need a die PHP function to be called at the end this is really important never leave an ajax function without a die at wordpress already have a safety precaution if you forget a die will point as zero appended to whatever result your page is going to have but always put a die at the end of an ajax function this is really important because you need to close that connection you need to shut down that open PHP Ajax connection to your admin function to your admin file so a die is really important so now we are acne the page so if we go back in our front-end we refresh we open the console but nothing is going to show up in the console pub we need to check actually it's open the network in the network section we have the list of all the files that have been loaded in the generation of this page so if we click load more first we're going to have one because is the variable is the parameter that we have inside our button but if we scroll down if we check in the network section we should have yes we order by name we should have a post method to admin Ajax dot PHP that we didn't have before if we open it we will see that the URL is requesting the Ajax with a post it's returning on ok so no error has been trigger and we are sending a bunch of information inside here that we can retrieve inside the parameters section and the parameters are the action that we're sending with JavaScript and the page that we are sending so the page is returning the page value that we're sending to the PHP function just has a test we can change this value to whatever we want for example I want it is call this data page this is awesome so if we refresh this page and we click one more is going to hear this is awesome because we are just simply echoing whatever information we want in this page so let's just leave a 1 let's save it now let's go back in our Ajax function let's remove a heckle now what we have to do we have to use the WP query to use this page and load new posts based on this page that it's going to be actually +1 because these page the current page is number 1 so we have to go +1 because we want to load the post of page 2 let's make clear ok let's create a new query we'd dollar query let's call new WP underscore query inside here we can specify an array of value it's going to be really small so I don't need to create custom arguments with an Iranian put the arguments aside I can put everything in line inside here I want to specify that post type then it's going to be equal to post I don't want pages I don't want anything else I don't want to specify the post per pages so by default the WP query will grab the post per pages declare in our administration panel what I want to declare though is the number of page that I need to specify to WordPress to grab those specific posts so if I write the value paged page D and it's actually equal missed the bigger than sign here we can specify the number then in this case is going to be two because we grabbed one and we add +1 so it's going to be two let's save it and now here we can just simply actually really easily copy this loop the post loop but we have to add our custom WP query our custom new WP query so let's inject our query variable inside the half post and if we have post let's inject D while and depose and let's leave these like that because we want the same effect we want to load all the template parts that match the post that we are loading so we're going to have the same result as the homepage and right before the die we have to always specify the WP underscore reset post data because we are updating d WP query post data so in order to not create any weird issues we have to reset the post data every time let's save it let's go back in our front-end let's close this now let's refresh and see if we broke something so lot more boom what happened we just loaded the gallery post format we just loader the video post title audio post title image post title so we loaded previously loaded post and just to check if we want to just prove that we did so at we actually load that for new post so if I put now 8 I should be able to see these 8 posts so let's say refresh now I'm seeing these eight posts so the last one is image title to test again let's say that the first two are the aside and gallery in the second is the link post format and the quote post format so if I put two posts per page i refresh here now I have just the aside and gallery if I click lot more I should get only the link and D quote lot more perfect link post format and quote post format this is great of course we have a bunch of issues first if we click lot more is going to load again in the same post because in these data attribute the data attribute is still just 1 so let's do a simple thing every time we load this huge increase of 1 so we're not in page 1 anymore we are in page 2 so let's do that with JavaScript and it's going to be really simple so first of all let's do it is only inside the success called that function so only if we are actually printing our post and everything went smoothly and worked we can update the page count to update the page count let's first create a new variable just right before page and it's called for new page and let's call the page variable plus plus and semicolon at the end to add just one and now we can update this data attribute or needs value with this new variable but we cannot actually do it because if we write this page stuff here we have to refer to the sensor load more did the actual button that we click we cannot use this because this is going to refer this time to the success function because we are inside success function we are not anymore directly underneath this class so in order to maintain the parent class of this button we have to declare another variable to carry on that this container so in this case let's use var that it's sometimes if you notice in other code you will notice this bar Det that declares only to be this this dollar this so inside that it's going to be stored the Sansa load more or whatever button you're actually clicking so you can use these depth variable to replace all this bar or these jQuery Declaration and the location of these that variable is not going to be affected or the pointing of this variable 2d Sansa load more button it's going to be is not going to be affected by gee location of where you call it because this variable is the clear at the beginning so even if you call it inside the success function is not going to be affected to update this data value you have to just simply put inside the brackets comma and then put the new value that you want here that if you want you can specify like manually five so these data page is going to be updated to five but we want to be dynamic so we're gonna specify the new page save it let's go back here let's refresh so now we have the first two let's load more we have oh it's skipping two mmm it's keeping the first is keeping two blog posts so let's check our JavaScript code if we did something wrong here oh sorry guys don't use this plus plus I always do this mistake so if you use plus plus these plus plus is going to increase the page number of one instead we have to use just plus one I always miss match these with PHP mmm I shouldn't do that so let's save it let's refresh back let's go back here let's load more and now we have the link and D a quote post format if we inspect the element of the button the data page is still 1 even if we updated if we click load more we're gonna not load anymore the same post but we're gonna load the next cue post so we are on page 3 if we load more we are on page 4 if we learn more we have the standard post title of course if we learn more nothing happens because we finished all the posts that we had before of course if you expect the element the data page is always 1 because the data attribute doesn't get updated inside the inspector dynamically but it actually works because we are loading previous posts we are not loading the same post so this code is working even if your console is not showing it buddy this is an issue of the console that the data attribute is not dynamically updated and you cannot see it but it's actually working because it's loading dynamically our post so in the next lesson we're going to take care of all the weird stuff that we have to take care when we do an eject call so first of all we have to change the URL every time we load more something we have to change these two maybe page 2 page 3 page 4 so we have to update the URL based on the low key we are then we have to create a little bit of animation a little bit on interaction for our users because this is really ugly if we click lot more boom it just jumps directly to wherever post is loading if we load more here we don't even see that new posts have been loaded so we have to create a nice smooth transition we have to create maybe a loading animation when the user clicks the button always give the user a response always give a feedback of a user action never leave the user waiting because if the connection is super slow is going to take a while to load so we have to create a little bit of JavaScript magic and CSS magic and the last thing but not least one if we reach the end of our post we should hide this load more we cannot leave it clickable and not working looks like it's broken but actually there are no more posts to load so we should specify this one and we're going to take care of all these styling thing in the next lesson we're going to also improve a little bit our PHP functions to retrieve better information and maybe have a little bit cleanup we're going to improve our Ajax function we're going to improve our CSS so the next lesson is going to be really awesome so it's pretty much it for this lesson hope you enjoyed if you did please give it a thumbs up or subscribe to my channel and if you have a couple of minutes as usual please take a look at the support me page on my website where you can find all different wages for me support my channel and help me to do better videos and better tutorials for you thank you again guys and as usual until the next lesson happy coding
Info
Channel: Alessandro Castellani
Views: 43,633
Rating: undefined out of 5
Keywords: wordpress, tutorial, php, jquery, ajax, web development, coding, help
Id: 7_lU7_JUS2g
Channel Id: undefined
Length: 41min 31sec (2491 seconds)
Published: Wed Mar 16 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.