One of the aspects of WordPress that people really like is the ability to add options. This is something that WordPress theme and plugin creators use heavily. They’ll create an options page or pages so that anyone who uses their theme or plugin can customize numerous different components of the theme… everything from look and feel, to contact form data, to portfolios, to just about anything else under the sun. Creating an option is as easy as storing adding an option:
<?php add_option('nbs_background_color', '#FFCC66'); ?>
Then to use an option in your webpages you just need to call get_option…
get_option('nbs_background_color')
Note: Notice that I used the prefix “nbs” (for Nine Bit Studios) before my option name. This is a common practice to prevent potential collision with other options because each option has to have a unique name. It’s very possible that another plugin that I have installed may have used the option “background_color”. By adding a prefix this is no longer an issue.
That’s all well and good, but there are a few potential downsides to this. For one, depending how your options are set up, it can be a fair amount of work to add, update, or remove options because you have to edit the code to register the option, edit the form for the user to set or update the option, edit the code to handle the values they set, etc. Hopefully, you have your theme or plugin options set up such that making changes is as smooth and easy as possible. It’s not a difficult process, but it can get a bit involved as the number of options that you want to handle grows in size and complexity.
Read More »
web development,
WordPressIn what follows, we’re going to take a look at how to create a Facebook Like Box in WordPress. If you create a Facebook Like box on the Facebook developer’s page, Facebook will give you some code to paste into your website. Something like the following…
<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&width=292&height=590&show_faces=true&colorscheme=light&stream=true&border_color&header=true" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:590px;" allowTransparency="true"></iframe>
This is an example of the iframe generated code, though there are a number of different types of code they’ll give you to choose from (HTML5, XFBML, etc).
You could certainly take the approach to paste this code directly into the PHP files in your WordPress theme where you want to show your Facebook Like box, but we’re going to do this in the form of a WordPress shortcode. That way we can pass in variable content to our Facebook Like box and we don’t have to update the raw code anytime we want to make a change.
Create a function in the location in your theme where you normally register your shortcodes. A lot of times this is the functions.php file but in the author’s humble opinion I believe that there are ways to keep your code more organized. Whether you are using functions.php or a class, add the following function to your code wherever it seems good to you…
function facebookBoxShortcode($atts, $content = null)
{
extract(shortcode_atts(array("id" => '', "path" => '', "showfaces" => 'true', "colorscheme" => 'light', "bordercolor" => 'white'), $atts));
$scheme = '';
$faces = '';
if ($colorscheme == "dark")
$scheme = "dark";
else
$scheme = "light";
if ($showfaces == "false")
$faces = "false";
else
$faces = "true";
return '<iframe id="'.$id.'" class="facebookBox" src="//www.facebook.com/plugins/likebox.php?href='.$path.'&colorscheme='.$scheme.'&show_faces='.$faces.'&border_color='.$bordercolor.'&stream=false&header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"></iframe>';
}
Then immediately after this you’ll want to register your shortcode…
add_shortcode('facebookbox', 'facebookBoxShortcode');
If you are registering your shortcode in a class — which I think is a good idea — then you’d use the following slightly different code instead…
add_shortcode('facebookbox', array($this, 'facebookBoxShortcode'));
What we are doing in our function is allowing for a number of different variables to be passed into our shortcode.
- id: This is where we can set the “name” of your Facebook box. It is used as an identifier if you want to have multiple different Facebook boxes on the same page. It can have any single word string value but each should be unique because (as you can see in the code), it maps to a CSS ID selector.
- path: This where you’d want to se the URL of the Facebook page you want people to “Like”. The default we have set is http://www.facebook.com/platform, but you’d want to change this to your own page.
- colorscheme: This setting could have the string value of either “dark” or “light”
- showfaces:
- bordercolor: Set the color of the border here. The default value is “white.”
We are now all set. Once you have your variables all configured the way that you want them, to use our newly implemented shortcode you could just add the following to your page or post…
[facebookbox id="myFacebookBox" path="http://www.facebook.com/yourpage here" showfaces="true" colorscheme="light" bordercolor="white"]
If you wanted to use this code outside of the WordPress Loop, such as your sidebar.php or footer.php files, you could use the following….
echo do_shortcode(‘[facebookbox id="myFacebookBox" path="http://www.facebook.com/yourpage here" showfaces="true" colorscheme="light" bordercolor="white"]‘);
May many Facebook “Likes” follow you wherever you go for all the days of your life.
Facebook,
PHP,
web development,
WordPress,
WordPress shortcodesIf you have done WordPress development for any extended perious of time, you inevitably go searching for different ways to do things. A lot of times what these tutorials will do will give you some code and say…
Just add the following snippet of code to your functions.php file and all will work great.
Having written tutorials for WordPress, I have been guilty of this. It’s a quick and easy way to give a user some functionality.
That’s all well and good when your first starting out, but after awhile if you’re not careful, you can end up just adding and adding and adding to your functions.php file and then pretty soon you have a massive document on your hands before you know it. It’s never good from programming perspective of maintainability and scalability to have large amounts of code concentrated that perform many diverse aspects of functionality located in a single place.
But what’s the alternative? I’m glad you asked. Well, by using classes in WordPress you can divide the code that handles the functionality for your website up into smaller parts each representing one piece of functionality. And in your functions.php file all you have to do is include the class. Then your functions file becomes a lot more lightweight and it is much nicer to work with when you have to use it for something else.
Let’s see an example of this. Let’s do something fairly standard that you’d normally do in WordPress: registering a shortcode. For the sake of example, let’s register a shortcode that does something simple like say hello. Maybe a previous tutorial would tell you to do something like put the following in your functions.php file…
function sayHelloShortcode($atts, $content = null)
{
return 'I am happy to say hello!';
}
add_shortcode('say_hello', 'sayHelloShortcode');
So now if you’d typed [say_hello] in into the editor in a page or post the text “I am happy to say hello!” would appear. Real world shortcodes are obviously much more complex than this but for the sake of example is best to keep things simple.
Now that’s nice. But as you add more and more shortcodes (and more complex shortcodes with large amounts of code inside the body of each function, your functions.php file could start to get out of hand.
So how can we solve this problem? Well it would actually make sense to take all of our shortcodes out of functions.php and group all of our shortcodes inside of one class. That way, we can have them all centralized in one location and if we want to add more, we’ll know where do do it. So if we wanted to add a shortcode to a class, this is how we’d do it. Create a new PHP file called Shortcodes.php and add the following…
<?php
class Shortcodes {
function __construct() {
add_shortcode('say_hello', array($this, 'sayHelloShortcode'));
}
function sayHelloShortcode($atts, $content = null)
{
return 'I am happy to say hello!';
}
}
?>
So the add_shortcode action will be executed inside the constructor of the class when the class is instantiated.
There is one distinctive difference when adding in action hooks or filters inside a class in WordPress. When specifying the callback function you have to specify that you want to access the callback function inside of **this** class. To do this you use the following syntax.
add_shortcode('say_hello', array($this, 'sayHelloShortcode'));
Whereas before you just used the string name of the callback…
add_shortcode('say_hello', 'sayHelloShortcode');
That’s really the only difference. After this you can create as much as you want and add as many functions as you want just as you were doing to your functions.php file and you can have the same functionality. Only now this piece of functionality is nicely wrapped up in your class. For example, if we wanted to extend the shortcodes class by adding more shortcodes, we can just add another “add_shortcode” to our constructor and add the callback function.
<?php
class Shortcodes {
function __construct() {
add_shortcode('say_hello', array($this, 'sayHelloShortcode'));
add_shortcode('say_something_else', array($this, 'saySomethingElseShortcode'));
}
function sayHelloShortcode($atts, $content = null)
{
return 'I am happy to say hello!';
}
function saySomethingElseShortcode($atts, $content = null)
{
return 'Something else';
}
}
?>
The other great part of this is that if you use classes to do other things like register custom post types, or add meta boxes, you can give your functions really simple names like “register” or “add” and there’s no risk having a conflicting function name from some other plugin or anywhere else because your function is wrapped up this class. You could use “register” as a function name in each one of your classes. That’s great! If you tried to do this functions.php you’d get a duplicate function definition.
But there’s one important final step we have to do and that’s actually create an instance of this class so that the code will actually run because the PHP classes don’t run by themselves they have to be declared and called. But this is easy enough. You can just create a variable and give it any name and set it equal to a new instance of the class right after the closing } of your class.
...
function saySomethingElseShortcode($atts, $content = null)
{
return 'Something else';
}
}
$shortcodes = new Shortcodes();
Then in your functions.php file just include this class and all the code inside of it will run.
include('Shortcodes.php')
You could even throw all of your classes in a “classes” folder and include it…
include('classes/Shortcodes.php')
That way you can keep your project directory nice and organized.
As far as naming your classes go, you’re usually okay but sometimes it’s a good idea to add a prefix to your class name. It’s conceivable that perhaps one of the plugins you have activated has also used a class named “Shortcodes.” So it’s a good idea to add a short sequence of characters to the beginning of your class name (e.g. MYNAME_Shortcodes). I use NBS (for nine bit studios). So my classes have names like NBS_Shortcodes, NBS_Meta, NBS_Portfolio. You just want to make sure that you don’t use the WordPress prefix WP_. WordPress uses this prefix so use your own to make it distinct from core WordPress classes.
So what are you waiting for? Get into your functions.php file and start grouping some of those functions into classes! You’ll be happy you did 😉
PHP,
WordPressThis post will teach you how to display an author box in WordPress. You may have seen small excerpts of information at the end of single WordPresss posts that give a little bit of information on the author (and sometimes there’s a picture there as well). Where do these items come from and how do you display these?
It turns out we’ll be getting the information from the “Users” section of the WordPress dashboard. If you click on the “Users” section, you can find the post author in a list of users. From there you can edit the “Biographical Info” section and that’s where we’ll be pulling the author info from. As for the image, we’ll just use Gravatar (what WordPress uses by default)
So to start, we will lay out our basic HTML. We’ll have a wrapper author box and an image and that we will float to the left of the author text. Add the following somewhere down near the bottom of your single.php file of your WordPress theme…
<div class="authorBox">
<h4>About the Author:</h4>
<div class="authorBoxImage">
</div>
</div>
Now we are going to want to add in the WordPress functions that we can call to get the post author information. Add following code to our markup…
<div class="authorBox">
<h4><?php printf( __( 'About the Author:', 'ninebit' ).' %s', get_the_author() ); ?></h4>
<div class="authorBoxImage">
<?php echo get_avatar(get_the_author_meta('ID'), 48); ?>
</div>
<?php the_author_meta('description'); ?>
</div>
<div class="clearout"></div>
So far so good. Note that number 48 when we’re calling get_avatar(). What that is saying is make the avatar 48px by 48px. If you wanted to make the avatar larger or smaller, you could pass in a different number here.
We’ve got our information down on the page, but it does not yet have any styling. So to style it up we’ll have to add the following CSS somewhere to our stylesheet…
.authorBox {
padding: 10px 10px 20px 10px;
overflow: auto;
border: 1px solid #eee;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-border-radius: 5px;
box-shadow: 0 0 2px #eee;
-moz-box-shadow: 0 0 2px #eee;
-webkit-box-shadow: 0 0 2px #eee;
}
.authorBox .authorBoxImage {
float: left;
margin-right: 10px;
border-width: 2px;
border-style: solid;
border-color: #fcfcfc;
box-shadow: 0 0 4px #999;
-moz-box-shadow: 0 0 4px #999;
-webkit-box-shadow: 0 0 4px #999;
}
The styling is fairly basic. If you wanted to add more bells and whistles to spice things up you could certainly do so.
Now if you go to one of your blog posts in your WordPress site, you should be able to see the post author’s avatar and information at the bottom of the post.
CSS,
PHP,
WordPressPosted by Ian on December 11, 2012 in
PHPmod_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. 🙂
.htaccess,
mod_rewrite,
PHP,
SEO