Share Tweet Reccomend

Pagination in WordPress

You say “tomato” I say “tomoto.” You “pageination” I say “pagination.”

Whatever you call it pagination is something that has abounded on the web since forever. If you’re not 100% sure what term pagination refers to, its the numbered links at the bottom of a page of results. There are different variations, but it often looks kind of like this…

1 2 3 … 37 38 Next > Last >>

If you enter a Google, Yahoo, or Bing Search and scroll to the bottom you will see these numbered links that allow you to the next page of results. That’s one example, but it shows up in many other contexts on the web. There are certainly other ways to do things. Infinite scrolling, for example, which we explored here is another way that sites can give users continual amounts of content. Nonetheless, pagination still remains a very popular way to organize things on websites.

Speaking of popularity, (on a seemingly unrelated note) even as we enter 2015 — the time of writing this — WordPress is still one of the most popular content management systems on the Internet. Despite new up-and-comers on different platforms such as Ghost on Node.js, WordPress is currently still the dominant force for blogging and/or publishing content on the web. So it seems like it would be worth knowing how to fit these 2 popular entities (pagination and WordPress) together. So in what follows, we will look at how to implement this.

So the function we’ll be creating is fairly straightforward. We’ll be making use of the $paged global variable which set to the page number that WordPress is displaying. Then based off of this, we do a few conditionals to figure out where we are in the range of pages.

function create_pagination_markup($pages = '', $range = 4)
{
    $markup = '';
    
    $showitems = ($range * 2)+1;
    
    global $paged;
    if(empty($paged)) $paged = 1;
    
    if($pages == '')
    {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if(!$pages)
        {
            $pages = 1;
        }
    }
    
    $pageText = __('Page','ninebit');
    $ofText = __('of','ninebit');
    $firstText = __('First','ninebit');
    $lastText = __('Last','ninebit');
    $previousText = __('Previous','ninebit');
    $nextText = __('Next','ninebit');
         
    if(1 != $pages)
    {
        $markup .= "<div class=\"pagination\"><span>".$pageText." ".$paged." ".$ofText." ".$pages."</span>";
        if($paged > 2 && $paged > $range+1 && $showitems < $pages) $markup .= "<a href='".get_pagenum_link(1)."'>&laquo; ".$firstText."</a>";
        if($paged > 1 && $showitems < $pages) $markup .= "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; ".$previousText."</a>";
    
        for ($i=1; $i <= $pages; $i++)
        {
            if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
            {
                $markup .= ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
            }
        }
    
        if ($paged < $pages && $showitems < $pages) $markup .= "<a href=\"".get_pagenum_link($paged + 1)."\">".$nextText." &rsaquo;</a>";
        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) $markup .= "<a href='".get_pagenum_link($pages)."'>".$lastText." &raquo;</a>";
        $markup .= "</div>\n";
    }
    
    return $markup;
}

Then all we need to do is echo it out where we need it…

<?php echo create_pagination_markup(); ?>

And voila, WordPress pagination.

,
Share Tweet Reccomend

Getting Mp3 Data Using PHP

If you look at the options that are out there for processing MP3 data in any language, you’ll find that most of the libraries that do the things that you want are pretty sizable because processing MP3 files can be an involved process. However, I wanted to find something that would give me a way to do simple processing of MP3s (given a link to the track on the internet) without having to load up a large library to do it. Since there wasn’t necessarily anything out there that would do exactly what I was looking for, I decided to write my own utility in PHP. PHP of course has the getID3 library which fits the aforementioned criteria, but I wanted something a little bit more lightweight.

At the outset, I would say it may not be the best idea to rely on what follows for much beyond the simple processing of files (especially if these are files are significant in size). Because we are pulling the file down using HTTP, processing can potentially be really SLOOOOW if you are handling multiple files of significant size. This method also assumes you know the bitrate of the file you are evaluating (and uses 128 Kbps by default). This class we’re going to write also requires at least PHP 5.3. So if you use anything below this, it will not work.

With all of that out of the way, let’s get started. We’ll begin by creating a class we’ll call MP3Data

<?php
class Mp3Data {

}
?>

Not too difficult. Of course, we’ll need to add our constructor and some class variables in. We’ll write the get_size_of_file function and the set_data a bit later on. For the purposes of this tutorial, we are going to assume a constant bitrate of 128. We’ll add an optional parameter to pass it in if you wanted to change this.

<?php
class Mp3Data
{
    protected $mp3data;
    protected $fileDirectory;
    protected $bitRate;
    protected $blockMax;
    
    public function __construct($filename, $bitrate = null)
    {
        $this->mp3data = array();
        $this->mp3data['filesize'] = $this->get_size_of_file($filename);
        $this->fileDirectory = fopen($filename, "r");
        $this->blockMax = 1024;
        
        if($bitrate) 
            $this->bitRate = $bitrate;
        else 
            $this->bitRate= 128;
        
        $this->set_data();
    }   
}    

We’ll use PHP’s ftell function to handle processing of our file and getting the current position of the pointer when the files is read. If you are not entirely familiar with ftell, not to worry. Just know that it will be very useful in determining the file duration from which we can figure out the track length.

We’ll also need a few other methods for our class…

<?php
class Mp3Data
{
    protected $mp3data;
    protected $fileDirectory;
    protected $bitRate;
    protected $blockMax;
    
    public function __construct($filename, $bitrate = null)
    {
        $this->mp3data = array();
        $this->mp3data['filesize'] = $this->get_size_of_file($filename);
        $this->fileDirectory = fopen($filename, "r");
        $this->blockMax = 1024;
        
        if($bitrate) 
            $this->bitRate = $bitrate;
        else 
            $this->bitRate= 128;
        
        $this->set_data();
    }   
    
    public function get_mp3_duration() {
        return $this->mp3data['duration'];
    }    
    

    public function get_mp3_filesize() {
        return $this->mp3data['filesize'];
    }

    protected function get_size_of_file($url) { 
        if (substr($url,0,4)=='http') { 
            
            $x = array_change_key_case(get_headers($url, 1),CASE_LOWER); 
            
            if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { 
                $x = $x['content-length'][1]; 
            } 
            else { 
                $x = $x['content-length']; 
            } 
        } 
        else { 
            $x = @filesize($url); 
        } 
    
        return $x; 
    }      
    
    
    protected function set_data() {
        $this->mp3data['length'] = $this->get_duration($this->mp3data, $this->tell(), $this->bitRate);
        $this->mp3data['duration'] = $this->get_formatted_time($this->mp3data['length']);
    }
    protected function tell()
    {
        return ftell($this->fileDirectory)-$this->blockMax - 1;
    }    
    
    protected function get_duration(&$mp3,$startat, $bitrate)
    {
        if ($bitrate > 0)
        {
            $KBps = ($bitrate * 1000)/8;
            $datasize = ($mp3['filesize'] - ($startat/8));
            $length = $datasize / $KBps;
            return sprintf("%d", $length);
        }
        return "";
    }

    protected function get_formatted_time($duration)
    {
        return sprintf("%d:%02d", ($duration /60), $duration %60 );
    }    
    

}

Now to get information from an MP3 file over the internet all we have to do is create an instance of this class and call it. This will return an associative array with all of the information that we need.

$dataArray = new Mp3Data("https://path/to/file.mp3");
echo $dataArray['length']; // filesize
echo $dataArray['duration']; // track time

Pretty neat, eh?

,
Share Tweet Reccomend

AJAX and WordPress

When the web moved from HTML4 to HTML5, the rise of AJAX based web applications came along with it. AJAX (which stands for Asynchronous JavaScript and XML) can mean a number of things but in practice it often refers primarily to the client/server interaction where JavaScript can be used to communicate with a server by making calls at various times under various conditions to send and receive data. This can be happening as often as you like in real-time without the user having to navigate to another webpage or refresh their browser (i.e. asynchronously).

AJAX

What is an example of this? Well, say I wanted to put a stock ticker on my webpage or in my web application. I could use JavaScript to make a call to a service like some stock-market API that will give me quotes on a particular stock, get the data back, and display it in the UI in a visually appealing manner. As these market prices update over time, I can periodically update the quotes that I’m displaying on the page. The format that the server returns data in really depends on the service you are calling. It can often be be XML (as the X in AJAX suggests) but another popular format is JSON. I actually like JSON a bit better, myself. The experience of parsing through everything in code just seems a bit cleaner so if there is the option to have the data you are trying to get returned to you in JSON, I’ll usually opt for that.

Because JavaScript is such a universally cross-platform language capable of running on so many different devices in different environments, this can be a great way for different applications to communicate with each other. The result, hopefully, is to give your users the best experience possible whether they are on desktop, mobile, tablet, or some other crazy device.

In the early part of the 21st century, something else that was and has been absolutely ubiquitous across the internet is WordPress. From it’s humble beginnings of being exclusively web-based blog software, it has transformed into essentially the most popular content management system (CMS) used for running small and medium sized websites or web applications.

In what follows, we can look at how we can undertake merging these 2 things together. We’re basically going to look at how we can send and receive JSON data to a WordPress database and read from and write to the tables within WordPress using AJAX.

Read More »

, , , ,
Share Tweet Reccomend

Create a Backup of Your WordPress Website Locally

… (the hard way).

There are probably a lot of plugins out there that will walk you through this process, but we’re going to be doing this the hard way. Why would we want to do this the hard way? Well, sometimes doing things the hard way gives you a better understanding of the ins and outs of a system as a whole and how things work. And sometimes trying to do things the easy way breaks down and you’re not sure how to resolve the problem. Not all plugins work out of the box and you have to go through all of the necessary support channels to resolve the issue.

However, if you know what needs to happen to accomplish something from the outset, you can forgo any of the headache that comes with automated processes going wrong. So, let’s take a look at how we might accomplish this.

Read More »

,
Share Tweet Reccomend

Autoloading Classes in PHP

One of the challenges you’ll often encounter in development is how to structure your application and how to keep your code organized in such a way that that it is both maintainable and possesses the ability to scale well. This is especially important if you are building a framework of some kind. There are many different PHP frameworks out there. For example, frameworks such as CodeIgniter and Laravel are PHP frameworks that follow the Model View Controller (MVC) pattern (although their respective implementations of it are quite a bit different). If you were to sit down to build something similar to one of these PHP frameworks, you would need to determine how your application would load up the files and resources it needed based on the user’s request. Autoloading in PHP can be a useful feature to automatically load your class PHP files if they have not yet been included. This is an especially useful feature if you are building a framework of some sort that will involve user named and user created PHP files (as MVC frameworks often do). Users have to create their own Model, View, and Controller files corresponding to the type of application they are building, but your framework is going to have to figure out how to include instantiate these classes. How can you do this when the names of the files will be dynamic? This is where autoloading can help.

If the index.php file were the entry point for your application, you might think we’d have to do something like the following before doing anything else in our application…

require_once('classes/MyClass1.php');
require_once('classes/MyClass2.php');
require_once('classes/MyClass3.php');
require_once('classes/MyClass4.php');
require_once('includes/functions.php');

This sort of scenario can lead to difficulties with dependency. If one class depends on another, if your application ever changes, you have to work extra hard to be sure that the relationships between your classes are maintainable. But with autoloading classes in PHP this may not be necessary.

How would we do this?

In the past the __autoload function was used. Say we had a file MyClass.php…

<?php
class MyClass {
    public function __construct() {
        echo "MyClass initialized successfully...";
    }
}
?>

But we haven’t included this class anywhere yet with the include or require functions in PHP. And then in another file later on (e.g. index.php) we have the following…

<?php
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// we've called a class ***
$obj = new MyClass();
?>

Amazingly, our class will work and get initialized. This is because the autoload function will load up or classes for us, which can be very handy. However, the spi_autoload_register function is now recommended as the new way of handling autoloading.

<?php

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');
?>

Or, as of PHP 5.3.0, we can also use an anonymous function…

spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

Having multiple autoload functions can be useful if you want to have different “types” of PHP files loaded. Files containing classes may not the only type of PHP file present within your application. And of course, you’ll still have to manage your dependencies between classes if any of your classes rely on other classes to function properly. But at least autoloading will take care of the task of loading up your classes as you need them in your PHP application.

,