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)."'>« ".$firstText."</a>";
if($paged > 1 && $showitems < $pages) $markup .= "<a href='".get_pagenum_link($paged - 1)."'>‹ ".$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." ›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) $markup .= "<a href='".get_pagenum_link($pages)."'>".$lastText." »</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.
PHP,
WordPressPosted by Ian on August 25, 2014 in
PHPIf 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?
PHP,
web development… (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 »
PHP,
WordPressPosted by Ian on November 7, 2013 in
PHPOne 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.
PHP,
web developmentA lot has been written about WordPress over the years with a lot of the literature describing how flexible it is as a CMS and how you can, with a little know-how and a little work, turn it into whatever you want it to be. Much of this flexibility comes from the ability to register custom post types, where you can create “post types” of any kind within the WordPress CMS. For example, if I were using WordPress to run a company website I could create a “staff” post type, where every entry that I create would contain custom fields for the name of the staff member, their picture, their e-mail, and links to social media profiles. The same thing goes for just about any other post type you could think of: image galleries, sliders, portfolios, etc.
And if there is some functionality that you need that happens to be lacking in the native installation of WordPress, chances are you’ll be able to find something close to what you need in one of the tens of thousands of plugins that exist out on the web. By combining these 2 features (along with a host of others) WordPress is an immensely flexible content management system (CMS) and this is likely one of the reasons it has gained such popularity since it’s inception.
In what follows, we’re going to combine custom post types and WordPress plugin development and create a plugin that registers a custom “portfolio” post type and wraps all of the functionality for both the front and the back end within it. So we’re going to need to to create fields for the name of the portfolio item, fields for featured images, and fields for links to where the project is showcased. After we get through everything, this should give you a good roadmap to create any post type/plugin that you like. In fact, a lot of plugins do little more than register post types inside of some generic WordPress plugin scaffolding code. Because there is so much you can do with custom post types, this is often all you need.
Read More »
PHP,
web development,
WordPress,
WordPress plugins