mod_rewrite is a rewrite engine used to rewrite requested URLs on servers running Apache. It is used to write URLs that contain query string parameters to SEO friendly and “clean” URLs. So for example if you had an an e-commerce site the following URL…
http://www.yoursite.com/index.php?category=clothing&type=shirts
That’s kind of ugly right? It would be nice if we could be rewrite this URL to something much nicer. Fortunately, we can do this using mod_rewrite…
http://www.yoursite.com/clothing/shirts
Pretty slick, eh? The functionality that handles how to rewrite URLs are defined in Apache server .htaccess files. In this post we are going to show a very basic example of how to rewrite some URLs. URL rewriting is no casual affair. It can take a long time to really understand and even then it can still sometimes get a bit confusing when URLs get more complex . Fortunately there are some good guides out there for anybody who is looking to learn more. I think that the tutorial at Nettuts is a great place for a more comprehensive look at URL rewriting as it goes much further in depth compared to what we are going to show today. What we are going to show is a really basic demo of what URL rewriting can do so that you can have a good starting point on your long (and hopefully happy) road of learning URL rewriting.
So to start, I am going to assume you have WAMP server (or MAMP) or XAMPP setup locally for a Apache/MySQL/PHP development environment. If you’re not sure how to do this, there are lots of great tutorial videos that can be found on YouTube. If you have a server somewhere out on the internet you could do this tutorial there as well, though it would be live for everyone to see.
To start out your’re going to want to create a new directory in your server (let’s call it “demo”). So if you’re running your server you should be able to go to http://localhost/demo or http://127.0.0.1/demo (if you are using port 80) and see the directory that this maps to. If you are using a different port, you’d just have to append that to the end of localhost (e.g. http://localhost:8976/demo). Let’s create an index.php file in this directory and add the following code so we can see if we are going to the right place…
<?php
echo 'Rewriting query string...';
?>
If you visit http://localhost/demo you see “Rewriting query string…” outputted to the browser, congratulations you are in the right place.
Let’s add the following item to our index.php file…
<?php
echo 'Rewriting query string...';
echo $_SERVER['QUERY_STRING'];
?>
If you visit http://localhost/demo now you’re not going to see anything different. However, if we visit http://localhost/demo?category=clothing we see the query string that we’ve added is output to the browser. You can make the query string as long as you like: http://localhost/demo?category=clothing&type=shirts&color=red&size=large
But as we’ve said before.. .these URLs are ugly. So now we are going to create an .htaccess file to rewrite these URLs and make them into clean URLs. Create an .htaccess file and place it in our demo directory.
Now add the following code to it…
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /demo/
</IfModule>
<IfModule mod_rewrite.c>
# If only version specified...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^(.[^/]*)[/]?$ index.php?category=$1 [L,QSA]
What this is saying is that if we have the mod_rewrite module installed, use the rewrite engine. We’re also going to use the base as /demo/. Below this we are actually going to define our rewrite rules.
Now if we go to http://localhost/demo/clothing what happens? We still see the query string because our rewrite rule is taking effect. Look at that. We have this nice url that still has access to the query string value (which we can do anything we want with in code either on the client side or the server side).
Now go to http://localhost/demo/books. Here again we see the query string value has changed to “books” is available to us even though we are using our nice URLs!
Not bad. Not bad at all.
This post will show you how to do some simple infinite scrolling for WordPress — or really, with a few small tweaks, any other system for that matter. A lot of times on websites when you have multiple pages of results you will see pagination at the bottom of the page with page 1,2,3 etc. and there will often be first, next, previous and last links in there as well. WordPress does this when blog posts, search results, comments and a number of other sets of results in a WordPress site are broken up into different pages. A lot of WordPress themes will show only the “Previous Posts “and “Next Posts” links by default (referred to as “paging”) but some themes will extend functionality beyond this to full on pagination.
Not all users are super exited about having to click links continuously to go to the next page of results. What infinite scrolling does is get the content found on those pages and append it to the current page so the user never has to click on the pagination links… making for a really nice user experience. You may have seen it on other websites you have visited. This tutorial will show you how to implement it in your own WordPress site.
99% of all WordPress themes’ index.php file has a call to get_header(), get_sidebar() and get_footer() (so I’m kinda assuming yours does as well). In your WordPress theme’s index.php file place the following code right before your call to get_footer();
<div class="xhrStatus"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
var currentPage = 2;
var containerItemSelector = "#main";
var postItemSelector = "article";
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "GET",
url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
data: "",
success: function(results) {
var item = $(containerItemSelector + " > " postItemSelector, results);
item.each(function() {
$(containerItemSelector).append($(this));
});
currentPage++;
},
error: function(results) {
if(results.status == 404) {
$(".xhrStatus").html('No more posts to show...');
}
else {
$(".xhrStatus").html('Error retriving posts...');
}
}
});
}
});
});
</script>
Now, there are a couple of variables that you’ll probably have to change to get infinite scrolling working properly on your site. These are the “containerItemSelector” and the “postItemSelector” variables. You can find them somewhere near the top of the above block of code. These variables tell the infinite scrolling code which container HTML DOM Element to put the next pages of posts in and giving it a wrapper for each post.
Let’s take a look at a very simple sample index.php file to illustrate what is being talked about here…
<?php get_header(); ?>
<div class="blog">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="postContent">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
<?php else: ?>
<div class="postContent">
<h2>Not found</h2>
<p>Sorry, no posts were found</p>
</div>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
So in the instance above, the div with the class “blog” is the wrapper element that we will be adding new posts to and each of those items are contained within a div with a class “postContent”. So we’d want to change our variables to the following…
var containerItemSelector = ".blog";
var postItemSelector = ".postContent";
So the entirety of the code of index.php would look like the following…
<?php get_header(); ?>
<div class="blog">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="postContent">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
<?php else: ?>
<div class="postContent">
<h2>Not found</h2>
<p>Sorry, no posts were found</p>
</div>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<div class="xhrStatus"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
var currentPage = 2;
var containerItemSelector = ".blog";
var postItemSelector = ".postContent";
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "GET",
url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
data: "",
success: function(results) {
var item = $(containerItemSelector + " > " postItemSelector, results);
item.each(function() {
$(containerItemSelector).append($(this));
});
currentPage++;
},
error: function(results) {
if(results.status == 404) {
$(".xhrStatus").html('No more posts to show...');
}
else {
$(".xhrStatus").html('Error retrieving posts...');
}
}
});
}
});
});
</script>
<?php get_footer(); ?>
What the code above does is execute an AJAX call to do a “GET” on the next page of results when the user has scrolled to the bottom of the page. The URL that we are getting the results from is represented by the “url” property in the $.ajax block of code. The PHP variable of this property will get the current URL and will get ?paged=[value of the currentPage variable] appended to the end of it. The value of the currentPage variable will start at 2 (since we are already on page 1) and will be incremented every time we do a successful GET of results.
This URL is WordPress’ structure for breaking up content into different pages. If you wanted to add infinite scrolling to a site being run on another system you could use a similar technique, but you’d just have to provide the proper URL for how that system divided things up into pagination.
Note too that we have also added an extra <div> with a class of “xhrStatus” right above the start of our <script> block. We are going to use this div to provide messaging if an error occurs in trying to get the next page of results. If we have reached the end of the results and there are no more posts to show, the server will return a 404 error.
If you wanted to, you could change the HTML element where this message gets displayed. You’d simply have to edit the selector value in jQuery where the message gets outputted to the one that you want.
If you wanted to implement infinite scrolling on different pages (e.g. a page template with custom post type results), you could simply add the above code to that page as well and make any necessary modifications.
Happy scrolling!
Today I am going to show you how to create very simple social sharing links for your WordPress blog. We all know that there are a gazillion different WordPress plugins out there to handle social media, but these may not always give you the exact customization that you want. Maybe you want to have text-only “share” links and the plugin does not support this. Maybe you want to use different icons than the ones the plugin provides. Maybe you want to format/position these icons differently from how the plugin does it by default. If this describes your situation, this post will help you get off to a good start with that.
So below are some basic WordPress ready sharing links for some popular social media websites. Please note that these links will work at the time this post was written. Websites often change their APIs and it is possible that the URLs to share out content on these social sites may have changed since the writing of this post… so be sure to check that all of these examples still work. If any do not, consult the website of the social platform in question and look for any advice on blogs and forums on how to change the link to something that will work with an updated API. And please do let me know if any of these do not work as well.
I have just kept the format of the links as plain text since it’s the most basic HTML that most people probably understand best. All you have to do is simplly paste the following code into the index.php or single.php or any other .php file of your WordPress theme. From there you can format and style these links however you like.
<a href="http://www.facebook.com/sharer.php?s=100&p[title]=<?php the_title(); ?>&p[url]=<?php the_permalink(); ?>" target="_blank">Facebook</a>
<a href="http://twitter.com/home/?status=<?php the_title(); ?>%20<?php the_permalink(); ?>" target="_blank">Twitter</a>
<a href="https://plus.google.com/share?url=<?php the_permalink(); ?>" target="_blank">Google+</a>
<a href="http://digg.com/submit?phase=2&url=<?php the_permalink(); ?>&title=<?php the_title(); ?>" target="_blank">Digg</a>
<a href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>" target="_blank">StumbleUpon</a>
<a href="http://delicious.com/post?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>" target="_blank">Delicious</a>
<a href="http://www.reddit.com/submit?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>" target="_blank">Reddit</a>
And that’s all there is to it!