Moving a WordPress site from a folder to the root

Sometimes you need to move a WordPress site from a folder to the root. Why would you move a WordPress site from a folder to the root? Well, in some cases, WordPress has been installed into a folder, and the root was redirected to that folder via htaccess. Google doesn’t like empty roots… So for this tutorial we are going to move to so you should replace these with your URL throughout the work

Steps to move a WordPress site from a folder to root

  • making a database backup
  • move the files
  • change the htaccess
  • change the database
  • change the links in the database to the new location
  • 301 redirect to keep the SEO
  • notify google about the changes


1. Making a database backup

For this migration, making a database backup is not just a way to sleep better at night, it’s mandatory. There are at least 2 ways in which you can break the database during the migration process, and it will HAPPEN. Good news is that it’s very easy to do a database backup if your hosting company has provided you with phpMyAdmin (most do). So fire up phpMyAdmin in your browser and look for the “Export” button.


This will open the Export view, where I suggest you go with the Quick option. This will save your database in SQL format on your desktop. Good, now if something happens (and it will) you can import the backup!



2. Moving the files

Now, if you FTP to your site, you probably have files more or less similar with the below screenshot: a folder where you currently have the blog, and some files in the root.



If you don’t need the files in the root to work anymore, then it’s quite easy: you should copy all the content in the “blog” folder to the root, except the .htaccess file. The reason you don’t have to copy the .htaccess file is that the .htaccess file in the root might contain redirect rules, or other rules you don’t want to lose. So let’s see how to change the htaccess file.

Note: if you only have FTP access, you need to copy all the files on the desktop then upload them back to the root of your site.

3. Changing the htaccess file

OK, so you basically have 2 htaccess files. One in the “blog” folder and one in the root folder. The .htaccess file in the blog folder looks probably like the screenshot below (the standard permalinks structure and the rewriteBase in the /blog folder.


And the .htaccess file in the root probably contains the rules to redirect from to


Good. We have to mix these in the root .htaccess file. We will simply add the WordPress standard rules below the redirect rules:


Let’s remove the referenced to the blog folder. Change RewriteBase to / and RewriteRule to ./index.php.

Note: we won’t remove the redirect to /blog just now. Let’s do the database change first.

4. Changing the database (changing the blog location)

There are two main locations you should change: the siteurl and the home. Fire up phpMyadmin and on the left side, look for the wp_options table


On the first page you will see the siteurl field, remove the /blog folder


And most probably, on the second page, the home url (likewise, remove the /blog folder


We are all set. Let’s remove the redirect to /blog in the root .htaccess file and give it a try. To do this, open the root .htaccess file and put a # in front of the 4 rules that redirect everything to /blog. Check if the site is working in the root.

Note: Firefox will remember the redirect to the /blog folder so you should first clear the cache.

5. change the links in the database to the new location

OK. now the site is working but if you look at any content image (or other resources added via the dashboard) you will see they still reference the /blog folder. The reason is that when uploading a media file, WordPress saves the full URL to the database. Of course you can live the “uploads” folder in the /blog/wp-content/uploads/ folder and everything will still work. But the new images will be uploaded to /wp-content/uploads (in the root) and that will tend to create a mess (duplicate files and so on). So right now we need a tool to check all the content in the database and replace the with The good news is that we have tools! One of these tools is the “WordPress (and others) Search and Replace Tool“. Download the file and upload it to the root, and rename it (for security purposes). I have renamed it db2.php so you can access it with This is how the first screen looks like (it will read the wp-config database details so no setting to be done by you):


 In the next screen you will have to input the old WordPress site address and the root address (watch for the way I put he ending /)


This will look throughout the database and replace the old URLs containing /blog with the root address (I scanned all the database tables like in the screenshow below).


Now it should be all in place and you can delete all the files in the /blog folder.

Note: if you have missing files, or something stopped working, you should restore the database backup you made at step 1

 6. 301 redirect to keep the SEO

Now, one of the very important steps in moving a WordPress site from a folder to root is to minimize the SEO loss caused by the moving of files. What happens is that Google looks for URLs (or people come to your site via URLS) that look like As we don’t have the blog located in the /blog folder, these visits will turn into 404 and you will lose traffic and Google will penalize also. The workaround this is to make 301 redirects between the old URLs and the new location. It seems that with a 301 redirect you will get almost 90% of the SEO juice of the original links. And the good news is that you don’t have to go URL by URL, you can work it out with only 1 line in the .htaccess file. SO edit the htaccess file and add at the end (you can also remove completely the redirect to /blog lines wich we previously commented with #) redirectmacth 301 /blog/(.*)$1


Let check if it’s working. Open the blog and go to a page It’s working right? Now add /blog/ like this and see if it’s redirecting to If it does, it means the redirect is working.

7. notify google about the changes

You can propagate the location change in 2 ways. Wait for Google to do it’s indexing (when they spider the content as usual they will start indexing the new URLs based on the 301 redirect) or you could go the fast way, by submitting a sitemap to Google Webmaster tools. It’s better to submit a sitemap because Google Webmaster tools will also report broken links or any other problems caused by the change of location. In my case I already had the Google (XML) sitemaps generator plugin installed, so I will show you which changes you need to do (if you don’t have it installed, go ahead and use it fresh to submit the new URLS to google)

  • change the XML file location (remove /blog from the custom location path)
  • Manually rebuild the sitemap

Now we’re talking! Not only that we have completely moved the WordPress site to the root location, but we also handled the SEO issue of having new URLs locations!

How to copy a WordPress site to a local computer

Sometimes you might need to copy a live WordPress site from the server to your local Windows PC to do some tweaking for a client. In this tutorial I will show all the necessary steps to copy the WordPress installation and make notes on things that might go bad along the way. I assume you already have Apache, PHP and MySQL installed (if not, you can have a look at Wamp)

Start by doing a WordPress migration plan

What happens most of the time is that people jump directly at copying the files and database then spend time wondering why the WordPress install is not running locally. I start by doing a migration plan – notes on how things are running on the live site:

  • where is wordpress installed? (not all wordpress sites are installed in the site root)
  • what is the permalinks structure
  • what WordPress version is installed
  • what plugins are installed
  • where is the uploads folder?

Finding out where WordPress is installed and the permalinks structure before the migration

Finding where is WordPress installed and the permalinks structure is very easy. You should look at the URL and the URL it’s going to tell you everything.


For example the above URL shows me the following things:

  • the domain I have to change to http://localhost is
  • the WordPress in installed under /blog
  • the site uses permalinks based on the name of the post (so there is a htaccess file I have to modify)

Finding out what WordPress version is installed

Knowing what wordpress version is installed is a must. You might think that as the theme and plugins are in a separate folder, you might just copy these from the live server and put them on top of a fresh local install. Well, that’s not true if the live site runs an older version which might break things on update. So the first think to look at in the WordPress admin is the “upgrade to the latest version” notification:


If the notification is present, then you can have a further look to see how old is the version running on the live server. To do that, after you are logged in the dashboard go to the WordPress logo at the top left, then click on “About WordPress”. The new page will show the real version


What plugins are installed and are these updated?

In the dashboard,go to the plugins menu and find out what plugins are installed and which need updated. Now, really, there is an issue with updating plugins on a WordPress site that was deployed by someone else. You can’t have any clues if the plugins where customized (and updating them will break the site) or they are raw installs from the site. What you can do is to look around for the specific versions of the plugin, download that specific version then do a compare between the raw version and what you have on the live site. You can never be too safe with this!

Migrating the WordPress install from a live server to a local Windows install

1. Copy the files

As explained above, if the site is running an older WordPress version then you might run into troubles if you just copy the theme and plugins and put them over a fresh WordPress. That’s why I usually take my time and download all the files, including the wp-admin and wp-includes folders which in theory should be left un-touched in any WordPress customization. So, in the local locahost folder I create a new folder with the site name, say “energyte” and copy via FTP the wordpress files there. So the new site should be available using the following URL: http://localhost/energybyte


2. Copy the database and import it locally

Once the database is imported locally you need to do at least 2 changes: change the siteurl and the home values. Go to the wp_options table and edit the siteurl si home values from to http://localhost/energybyte (well, this is just an example site, you should replace with your domain)


3. Change the htaccess file to point to the localhost structure

Now, as the live wordpress installation is done in the /blog folder and we know the site is using permalinks from the post title, the htaccess file looks like this:


Because the local site is installed in http://localhost/energybyte (meaning in the energybyte folder) we need to change RewriteBase to /energybyte/ and RewriteRule. /energybyte/index.php [L]

4.Change the connection to the database

One last thing to do is to change the connection to the dabase in the wp-config.php file. Open the file with your preferred editor and change the values to whatever connection details you’re having locally. If you are using wamp, then the user is root and password is empty:


You should be up and running at this time. Open a browser and point it to http://localhost/energybyte

What if you don’t have the wp-admin password?

Sometimes the customer gives you the WordPress files and database by talking with the hosting company and are “afraid” to hand over the username and password to the live site. So in this case, even if you have installed WordPress locally like a charm, you can’t access the dashboard. Using the recovery password feature won’t work as is going to send the recovery details back to the owners.

You can solve this issue 2 ways: you change the admin address email to one of your emails then use the password recovery feature, or create another user and make it admin. If the WordPress settings allow to create a new user from the wp-admin interface, I usually like better creating a separate user (if I import the local database to the live site later I won’t risk having my own email address and password there. So create a new user

Creating a new admin user in WordPress

If the WordPress install allows you to register new users, use the following steps to make an admin user:

  • go to wp-admin and click on “register”
  • Create the new user
  • Go to the database and locate the ID of the new user in the wp_users table (in this example ID=12)
  • Go to the wp_usermeta table and look for the wp_capabilities row for the column user_id=12 and replace the standard subscriber capabilities with these: a:1:{s:13:”administrator”;b:1;}

You’re good to go!

How to remove the read more link in posts

There are cases where you want just a section of the content to appear on the home or category page and that people should click on a link to read the rest of the article. The default WordPress behavior is that if you insert  the “read more tag” into the content it will split the content and do just that, display a read more link to the details page. In the PHP code, the content is displayed using this tag: <?php the_content(); ?>

However, the read more link will appear in the content (at the end of the text) and you might want to format the way the read more link appears. There are more ways to customize the read more link.

Ways to customize the read more link

  • One way would be to use the excerpt using the PHP code: <?php the_excerpt(); ?> then place the read more link using the permalink like this:  <a href=”<?php the_permalink() ?>” >Read more</a>. This allows you to customize the read more link, place it in a div or span and apply CSS on it. However, using the excerpt has some disadvantages:
    • It strips the HTML content (so the text will appear as plain text) and it strips the images
    • It’s limited to 55 chars so you can’t decide from the content where you want to end the teaser text
  • The other (and better) way is to use the_content and customize the display.
    • One way to remove the read more link is to replace the “read more text” with an empty space like this <?php the_content(“”); ?>
    • The other better way is: <?php the_content(”,FALSE,”); ?>


SEO for your WordPress blog

In this tutorial you will learn the basic SEO rules to follow when adding posts to your WordPress blog and how to use YOAST WordPress SEO plugin to optimize the blog content.

Basic SEO rules for your WordPress blog

If you’re reading this you probably already heard about SEO and you want to get a bit more traffic from search engines to your WordPress blog. Of course, SEO is quite a vast area, and unless you have loads and loads of time available to learn and do SEO it might be better to hire a SEO agency to improve your blog. But what a SEO agency will have a hard time with, it’s quite easy for you: writing the blog content following basic SEO principles. I mean you already write the content, so what if you pay attention to SEO a bit? (Of course writing articles solely for SEO is bad because it’s not going to benefit your readers). So here are a few rules you can easily apply when you’re writing your regular blog content (this does not intend to be a complete list):

  • Pay maximum attention to your blog post title. A typical WordPress installation uses the post title for: the HTML title (appears on the very top of your browser as in the screenshot below), the URL (read the point below), and the <h1> tag of the page. Exactly the 3 most important SEO content elements.
    It’s paramount.HTML title

    Therefore, when planning for a new post, you probably have in mind the idea the post needs to communicate. The post title should be very clear what the post is about and include the keywords that you think people will use in Google to find your article. In my post I used as an example for the screenshots I wanted to talk about google sitemaps and wordpress so the keywords I wanted to make sure I have in the title were: google sitemaps and WordPress. You can also see the permalink which I describe below.Wordpress post title

  • The permalinks. Search engines will rank higher the pages that have an URL with related keywords to the content of the page. But, the default WordPress installation makes links to posts something like which is not very SEO friendly. As explained above, WordPress could make the URL out of the post title with the right settings, so you should make them. To do these settings look into the WordPress dashboard and in the “Settings” menu go to “Permalinks”. I usually go for month and name. This will set WordPress to automatically create the URL to your post from the date of publishing and the keywords from your post tile (and you can also manually adjust the created permalink).
  • Headings. Search engines place a good deal of importance on the headings available in the content. Most probably the <h1> tag (the most important) is created by WordPress automatically out of the post title, so you should take care of the <h2>, <h3> tags. This means you shouldn’t write plain text to your posts. You should divide the content into sections and for each section come up with a heading title that is relevant to the page and that section. It helps the readers and it help SEO.
  • Keyword density. If your post is about Google sitemaps and WordPress and these are the keywords you want people to use in the search engines to reach your page, then these keywords should appear in a reasonable amount in the post content. Overstuffing keywords is bad, not having enough is bad as well, so you need a good balance.
  • Internal linking. When you are writing a post, in some cases there might be some related posts you already wrote that could bring more details to the reader. So, why not link from specific words to the relevant related content? It helps the reader understand better what you’re writing about, and it’s good for SEO.

Using the YOAST WordPress SEO plugin (to make things easier)

Now, of course you can do all these SEO optimizations on your content quite easily, but you need to do a bit of outside research and check manually or with a tool how your page is looking SEO wise after publishing the post. There are also quite a few SEO plugins that help you add a better HTML title and Meta Description to the page. The usual process is something like this: you write the title thinking about the keywords => write the content => publish the post => check the page’s SEO => edit the post to make SEO improvements => publish (update) again => check for SEO. Quite time consuming. Or you could use the YOAST WordPress SEO plugin and do all these on the fly; what makes this plugin differently is that besides giving you the options to better manage the HTML title, meta description and other SEO related elements for the entire blog, it evaluates the post content from within the “Add new post interface” and lets you know what should be improved. So it cuts the need of an external SEO tool.

Installing the YOAST WordPress SEO plugin

Installation is quite typical; download the plugin from here, upload it to the “wp-content/plugins/” folder and go to the “Plugins” menu in the WordPress dashboard:

Wordpress Plugins

Locate the plugin in the list and click on “Activate” (if you don’t find it, make sure you are in the inactive plugins list (click on the inactive link, just above the plugins list)

Activate plugin

Once is activated, a new menu called SEO will appear bellow all the other menus in the WordPress dashboard.

Yoast WordPress SEO

Changing the HTML titles and meta descriptions with the YOAST WordPress SEO plugin

Before doing any post content optimizations, you should do some SEO optimizations site wide, using the plugin. Go to the “Titles” menu and in the screenshot below you can see the plugin gives you the ability to create a template for the HTML title and meta descriptions for various page types. Usually for the pages and posts you can do individual customizations while editing the content (the settings you do in the “Titles” menu are used if you don’t manually change them for each post), but for other pages, the settings you do here can’t be customized elsewhere (for example the search page, the authors page). Make sure you use relevant keywords when composing the title and description (the title should be less than 70 chars and the description less than 141).

YOAST SEO titles

For some titles and descriptions you can have the plugin filling in some tags which is great because the titles and descriptions shouldn’t be identical, they should be relevant to the actual content of the pages. For example, for the post title you can fill in the field like this: Wp Starter: %%title%% – this will make the post: “Wp Starter: SEO for your WordPress blog”

YOAST titles

Other YOAST WordPress SEO site wide options

If you go to the “Indexation rules” menu, the plugin will give you the ability to block some sections for Search engines. Why it might be good? By default, WordPress generated more views for the same content (which search engines don’t like because it’s duplicate content). Therefore it might be good to block for example the author categories. But as the plugin warns, use with care!

YOAST indexation rules

The “XML sitemap” menu gives you the option to create a XML sitemap. However I like to have better control over it, and you can install a separate WordPress XML sitemap plugin. The “Permalinks” menu gives you access to more advanced settings over the typical WordPress permalinks (which you should enable from the Common settings window as explained above). However I feel these are a bit of an overkill.

Advanced permalinks

The “RSS” menu comes quite handy. It allows you to easily customize the content of the standard WordPress RSS output.



Post and page SEO optimizations

Here comes the nice part of the YOAST WordPress SEO I was telling you about. While you’re editing the post content, below the editor you will see the YOAST window that helps you analyse the content on the fly (you need to save the post first).

In the “General tab”

  • The Snipped Preview shows how the page will look like in Google searches. It gives you an overall idea on the page title, link (URL) and description.
  • In the Focus Keyword field, fill in the most relevant keyword for the page (what you want people to use in Search engines to find your page). Tada! It gives you a quick view on how well you did SEO wise on the article heading, page title, page URL, content and meta description.
  • The SEO title field let’s you customize the HTML title of the page beyond the automatic WordPress title creation (or the template you did in the “Titles” menu – see above)
  • The Meta description let’s you make a custom meta description for the page (the default template is created on the settings you did in the “Titles” menu – see above).

YOAST general tab

The “Page Analysis” tab

The “Page Analysis” tab is even cooler. It gives you a quite detailed overview on how your page is standing SEO wise. It gives you an insight over the keyword usage throughout the content, links, images, ease of read and more!

YOAST page analysis

The “OpenGraph” tab

It’s a bit unrelated to the rest of the functionalities but, the “OpenGraph” tab comes in handy if you are publishing the pages to Facebook. You can customize the description of the page (what Facebook will show as a page description).

YOAST OpenGraph


How to add Google Sitemaps to your WordPress blog

In this tutorial you will learn how to automatically generate and submit a sitemap to Google Webmaster Tools from your WordPress installation.

Once your site is up and running you might want to take some steps to optimize the site for search engines so you could get some more traffic. But before you start learning about SEO (search engine optimization) you should first measure the results you got and analyze your status. Without measuring, any optimization effort is prone to failure – you should be able to check if it has any effects.

There are more tools you could use to analyze your traffic, including some very good free ones offered by Google: Analytics and Google Webmaster tools. Google Webmaster Tools is especially important because not only that you can learn more about your site, including which pages are in the Google index, crawling stats, popular search queries, sites linking, but by submitting a sitemap with all your site pages you can increase the number of pages that Google indexes.

Add your site to Google Webmaster Tools

Google Webmaster Tools are available here. Click on “Sign in to Webmaster Tools” button and use your Gmail email address to sign-in/sign-up.

Google Webmaster Tools

After login, in the Dashboard page, click on the “Add a site” button.

Add a site to Google Wemaster Tools

In the pop-up that opens, add the URL of your site (for example

Add site URL to Google Webmaster Tools

The next step is to verify the ownership of the site; basically you should upload a file to your site and Google verifies it.

Verify site to Google Webmaster Tools

You should download the HTML verification file, then upload it to your site. In the screenshot below I’m using Total Commander to upload the file to the site root. In the left panel I have the file I have downloaded from the Google Webmaster Tools and in the right panel I have connected via FTP with the server. To upload the file, I select it on the left side and click on F5.

Upload verification file to Google Webmaster Tools

After upload the file, go to Google Webmaster Tools interface and click on “Verify”. If everything is ok, the Dashboard should look something like in the screenshot below. But wait! There is no data! That’s the moment we should generate a sitemap and submit it to Google.

No data to Google Webmaster Tools

WordPress plugin to generate Google sitemaps for Google Webmaster tools

After a bit of research I found out that the easier way to generate a Google sitemap for a WordPress site is to use a plugin. For this tutorial I used the Google XML Sitemaps plugin that you can download from here. This plugin reads the WordPress database and generates the sitemap files and submits them to the Google Webmaster Tools.

To use the plugin there are a few steps:

  • Upload the plugin to the WordPress plugins folder
  • Activate the plugin in WordPress dashboard
  • Set the plugin options

To upload the plugin with Total Commander in the right panel browse (on the server) to wp-content/plugins folder. In the left panel, double click on the “” file. This will open the archive and you can see the plugin folder inside. Click on F5 to upload the entire folder to the plugins folder on the server.

Upload Google XML Sitemaps WordPress Plugin

Once the plugin files are uploaded, go to the WordPress dashboard and go to the Plugins menu:

Go to plugins in the WordPress Dashboard

Next step is to activate the plugin. Locate the “Google XML Sitemaps” and click on the “Activate” link.

Activate Google XML Sitemaps plugin

Before the plugin starts generating the Sitemap files, you should upload some empty sitemap files. Download the sitemap.xml file and sitemap.xml.gz files and upload them to your site root. Using Total Commander, click F5 to upload the files from the left panel to the site root.

Upload empty sitemap files

After the files are uploaded, you should change the file attributes – the files should be writable by the plugin. Select the files on the server using “Insert” and click on Files/Change Attributes.

Change files attributes

In the pop-up window set the attributes to 777.

777 rights

Google XML Sitemaps plugin options

Once the files are uploaded and the plugin has the rights to write to them, it’s time to set the plugin options. In the WordPress dashboard go to Settings/XML-Sitemap.

Wordpress Settings menu

This will open the plugin options page. The first thing to look after is the Location of the sitemap file. If your WordPress is installed in the site root, the location of the sitemap file should be something like If the WordPress is located in a different folder, you should check the sitemap file location.

Sitemap files location

The Basic Options are set by default, but you could have a look and see if you need to change anything.

Sitemap Options

You should also have a look to what content is actually submitted from your blog. Submitting all the content is not necessarily the best option as WordPress generates different views to the same content and submitting everything will mark some pages as being duplicates (duplicate pages are bad for SEO).

Sitemap Content

There are a few other options that you can play with, but I have covered the basics. It’s time to generate the sitemap for the first time. On the top of the page, you can see the sitemap status:

Generate sitemap

Click to generate the sitemap, and if everything is set correctly, the result should look something like in the screenshot below:

Generate sitemap results

Final steps

After generating the sitemap on the server, you should submit the sitemap to Google Webmaster Tools (this should be done only once, as the plugin will submit the sitemap automatically after). Go to the Google Webmaster Tools dashboard and click on “Submit sitemap”. In the pop-up fill in the path to the sitemap file:

Submit sitemap URL

You’re done! In a few days you should get statistics on your site.

How to restrict users access to certain posts in WordPress

In this tutorial I will show you how easy is to create posts that are restricted to the general public and only available for users belonging to a specific category. To do this, we need 3 things:

  • a way to mark a post as being available to a specific category of users
  • a way to create the special users category
  • restrict the content view

The easiest way to do this is by using the Members plugin by Justin Tadlock

Installing the Members plugin

To install the Members plugin:

  • download the Members plugin from here.
  • upload the Members plugin to the /wp-content/plugins/ directory
  • Go to the plugins menu:

Add new WordPress Plugin

  • Activate the Members plugin

Enable Members plugin

Using the Members plugin

The Members plugin is relatively simple to use. First thing is to activate the plugin components that you are actually going to use (the plugin comes with more capabilities and you can select which ones you want to use). Go to the settings menu and click on the “Members components”

Members components

Enable the features you are planning to use. Each feature is described, if you are not sure which ones you need, enable them all:

Select component

As soon as you have enabled some features, you need to assign the capabilities to an existent role. Go to the Users menu and click on the “Roles” tab.


Assuming you want to give the new capabilities to the administrator role, click on the “administrator” link

Edit roles

Add the new capabilities to the administrator role. For example: “edit roles”, “delete roles”, “create_roles”, and most importantly “restrict content”


With the “restrict content” capability assigned, you can already mark posts as being restricted to certain user types.

Creating a new user role

If you don’t want to make the content available to one of the standard WordPress roles, you can create a new role, then assign the right to view content to that role in the post editing page. To create a new user role, go to the Users tab and select the “New Role” page.

New role

In the new window, create a new role and assign a label to the new role:

Role label


Creating restricted content

Creating restricted content is very easy. Go to edit/add new post and below the editor you will see now the list of user roles where you can select which roles have the right to view the content.

Restricting content

Here is what a regular user will see in the front-end:

View restricted content

Testing that the special users are able to see the restricted content

Right now, you know that the content is not available to regular users, but is it available to the users that are supposed to view the content? To check this, let’s create a new user and assign it the special role you have created earlier.

Add new user

Logout and login as the special user:


Go to the front-end, and voila! The restricted content is available for you!

View Content


How to display content from the database in your WordPress plugin

Let’s say you’re building a plugin that needs to display a list of database entries in a special page in the WordPress dashboard. Something that looks like this:

Retrieve content from the database in WordPress dashboard


I have covered previously how to create a new page in the WordPress admin dashboard so let’s see now how you can select the database content and display it in a table. First you need to create the table layout, and for this the easiest way would be to create some divs and place some css in a css file to arrange the cells.

Including a CSS file in your plugin file

Let’s create a css file called wps-poll.css inside the wps-poll plugin folder.

The CSS code is very easy. There are some entries for the table header and some entries from the results retrieved from the database.

For the table header:

.poll_item_no_head {



.poll_active_head {

For the entries retrieved from the database:

.poll_item_no {



.poll_question {

.poll_active {

With the CSS file created, it’s time to include it in the plugin file. In one of my previous tutorials I have explained how to find the path to files in the plugins folder, so let’s create a function that includes the CSS file and add an action for it:

function my_plugin_admin_styles() {
$url = plugins_url(‘wps-poll.css’, __FILE__);
wp_register_style( ‘wps_poll_Stylesheet’, $url );

wp_enqueue_style( ‘wps_poll_Stylesheet’ );
add_action(‘admin_init’, ‘my_plugin_admin_styles’ );

Right now, if you have created the admin page as explained in my previous tutorials, you should be able to go to the WordPress dashboard, click in the menu on the newly created admin page and if you check the source code, the style file should be included in the head.


Creating the table layout using DIVs

With the CSS file in place, we should write the DIV that will be the header of the table:

<div style=”width:470px; border:1px solid”>
<div class=”poll_item_no_head”>NO</div>
<div class=”poll_question_head”>Poll Question</div>
<div class=”poll_active_head”>Active</div>

<div style=”clear:both”></div>

This should look something like this if you got the code right:

Retrieve content from the database in WordPress dashboard


Retrieve content from the WordPress database

For this tutorial I have created a table “wp_wps_poll” in the WordPress database, with the following fields “id_poll”, “active_poll”, “question_poll” and inserted a couple of entries (that you can see in the first screenshot). So now, we have to create a function that will select the entries from the database, then generate the table that displays the entries.

To retrieve content from the WordPress database you can select a variable, a row, a column or multiple rows. As we want to retrieve all the entries from the “wp_wps_poll” table, we will declare the global variable $wpdb and use get_results that retrieves multiple rows.

The result of the function is an array, so, to display the content, you have to use a foreach statement that will output all the entries.

Let’s start:

function wps_poll_options_page () {
global $wpdb;
foreach () {

Write the SQL select using get_results

This will select all the entries in the wp_wps_poll table, ascending order after id_poll and should be added after declaring the global variable $wpdb:

$poll_list = $wpdb->get_results(“SELECT * FROM wp_wps_poll Order by id_poll ASC”);

Let’s add the table header that we have created earlier (to do this, we have to split the function and insert the HTML code in between):

function wps_poll_options_page () {
global $wpdb;
$poll_list = $wpdb->get_results(“SELECT * FROM wp_wps_poll Order by id_poll ASC”);

<div style=”width:470px; border:1px solid”>
<div class=”poll_item_no_head”>NO</div>
<div class=”poll_question_head”>Poll Question</div>
<div class=”poll_active_head”>Active</div>

<div style=”clear:both”></div>

foreach () {

Using foreach to retrieve the content from the get_results function

Note: the code is written this way to make the explanation simple. We create the $poll_no, $poll_question and $poll_active variables that will take the values from the array, then the $first_cell, $second_cell and $third_cell variables mix the DIV that make the table layout with the content retrieved from the database. Echo-ing outputs the results:

foreach ($poll_list as $poll) {
$poll_no = intval($poll->id_poll);
$poll_question = $poll->question_poll;

$poll_active = $poll->active_poll;
$first_cell=”<div class=\”poll_item_no\”>”.$poll_no.”</div>”;
echo $first_cell;
$second_cell=”<div class=\”poll_question\”>”.$poll_question.”</div>”;

echo $second_cell;

$third_cell=”<div class=\”poll_active\”>”.$poll_active.”</div>”;

echo $third_cell;

echo “<div style=\”clear:both\”></div>”;

The complete code (CSS not included)

function wps_poll_options_page () {
global $wpdb;
$poll_list = $wpdb->get_results(“SELECT * FROM wp_wps_poll Order by id_poll ASC”);

<div style=”width:470px; border:1px solid”>
<div class=”poll_item_no_head”>NO</div>
<div class=”poll_question_head”>Poll Question</div>
<div class=”poll_active_head”>Active</div>

<div style=”clear:both”></div>
foreach ($poll_list as $poll) {
$poll_no = intval($poll->id_poll);

$poll_question = $poll->question_poll;
$poll_active = $poll->active_poll;
$first_cell=”<div class=\”poll_item_no\”>”.$poll_no.”</div>”;
echo $first_cell;
$second_cell=”<div class=\”poll_question\”>”.$poll_question.”</div>”;
echo $second_cell;
$third_cell=”<div class=\”poll_active\”>”.$poll_active.”</div>”;

echo $third_cell;

echo “<div style=\”clear:both\”></div>”;

How to find the URL to the plugins folder when creating a plugin

If you’re building a plugin, you will probably get to the point where you would like to include files from the plugin folder. As building a plugin means the code should work no matter how the blog is configured, you should use a function that retrieves the path to the plugin folder, then hardcode only the name of the file that needs to be included.

As usual, WordPress comes to the help with a special function that retrieves the path to the plugins folder: plugins_url.

Using plugins_url to retrieve the path to the plugins folder in WordPress

Plugins_url can be used to retrieve the path of images, CSS or Javascript files that are placed inside the plugin folders. We have 3 situations:

  • you also hardcode the folder of the plugin (let’s say the plugin folder is wp-polls and we want the path to the css file):
    $url = plugins_url();
    echo $url;
    wp_register_style( ‘wps_poll_Stylesheet’, $url . ‘/wps-poll/wps-poll.css’ );
    Note: don’t change the plugin folder! Or if you do, remember the change the hardcoded part as well.
  • You let plugins_url to retrieve the path using the $plugin parameter:
    $url = plugins_url(‘wps-poll.css’, __FILE__);
    echo $url;

    wp_register_style( ‘wps_poll_Stylesheet’, $url );
  • If the files are in a subfolder you should use dirname(__FILE__):
    $url = plugins_url(‘wps-poll.css’, dirname(__FILE__));
    echo $url;

    wp_register_style( ‘wps_poll_Stylesheet’, $url );

Creating a WordPress Posts Separator

Do you want to make a separator between posts in WordPress (and don’t know how to handle the last post case where you don’t need to show the separator?) This requires a bit of coding, but it’s quite easy to do. There are a few steps needed to create a WordPress posts separator:

  • identify what php page generates the WordPress posts list
  • locate "the loop"
  • Insert the separator code
  • Handle the last post case (where you don’t want to show the separator)

Identify what php page generates the WordPress posts list

First thing first, the pages where you need to add the separator code for the WordPress posts list is inside the wp-content/themes/your_theme_name folder. If you are not sure what theme the site is using, login to the WordPress dashboard and go to Appearance and look for the "Current theme". The theme folder name should be similar to the theme name you can see in the dashboard.

Second, depending on where you are in the WordPress site, the list of posts can be generated by various php files inside the template directory. For example, if you are on the homepage, the list of posts can be generated by either home.php or by the index.php. If you are on a non homepage, then the list could be generated by category.php or some other page where the loop is inserted (for example if special template pages are created). The first step to locate what page handles the posts list is to have a look and understand the WordPress Template Hierarchy then edit the php page that you believe handles the posts lists and add a bit of text to it, refresh the site page in the browser and search for the text you just added. If you can locate the text, then you have located the right php file.

Locate "the loop"

"The loop" is the specific WordPress code that generates the list of posts. While the_loop content might be different from implementation to implementation, you should be able to easily recognize the_loop start:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>  

and the_loop end:

<?php endwhile; else: ?>  <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>  <?php endif; ?>  

Insert the separator code

The separator can be anything: a line, an image, a block of text. If it’s an image, the best practice would be to insert a div and style it to point to an image. Using styles it’s easier to change the look&feel of the separator later. Let’s see a separator example:

<div class="post-item-divider">&nbsp;</div>

To make this div actually display something you need to locate the .css file inside the theme folder and add the new class to it. The new class might look something like this:

.post-item-divider {

Of course, you need to upload the separator.jpg image inside the images folder.

To see if the separator shows, add the div just above the <?php endwhile; ?> Most likely the separator image should appear between the posts, problem is that it’s going to appear after the last post as well.

Handle the last post case (where you don’t want to show the post separator)

To handle the last post case as a separate case, you need at least 3 things:

  • find out how many posts are displayed on the page
  • find out the current post number
  • remove (or alter) the separator code if the current post number equals the total number of posts on the page

How many posts are displayed on the page?

You might think that the number of posts displayed on the page is the number of posts per page you set at the settings page in the WordPress dashboard. Well, that’s true, unless you are in a category or page that has less than the maximum number of posts you set in the WordPress admin. So, we need a bit of code to find out the number of posts on the current page. The Wp query function comes to the rescue, because it has a property called $post_count that indicated the number of posts being displayed.

So $wp_query->post_count gives us the total number of posts on a particular page.

Find out the current post number

As in any loop, "the_loop" in WordPress executes the code "while" there are posts. So basically the posts content is shown each time a loop takes place:

the content
the content
the content

If there is a way to count the loop number, then we know the content inside the look belongs to a particular loop and we can check if it’s the last post. There is a Wp query property to count the number of posts: current_post.

So $wp_query->current_post gives us the current loop number.

Compare the total number of posts with the current post number and remove the separator code

The only thing to do right now is to compare the total number of posts with the current post number and remove the separator code. First, we need to do and if statement and echo the separator code inside:

<?php if () {
echo ‘<div class="post-item-divider">&nbsp;</div>’;
} ?>

Let’s see the condition that compares the total number of posts with the current post number:

($wp_query->current_post) < ($wp_query->post_count-1)

What this condition says is: if the current post number is smaller than the total number of post -1. For example, if there are 9 total posts on the page and we are at a post number smaller than 8, show the separator. Hey, but wait, doesn’t this mean that the last post to show the separator is <8, so 7 which doesn’t put a separator between post 8 and 9? Well, the numbering of current posts starts from…0.

Here is the complete code that needs to be added inside the_loop:

if (($wp_query->current_post) < ($wp_query->post_count-1)) {
echo ‘<div class="post-item-divider">&nbsp;</div>’;

Adding a form to the WordPress admin to save new options

In one of the previous tutorials I have shown how to create a new page in the WordPress Admin dashboard where you can create additional settings fields. If you followed that tutorial, you probably now have an empty page that shows in the WordPress admin menu.

In this tutorial I will explain how to create a form and save the values to the WordPress database.

Do you have complex settings or easy ones to add to the WordPress admin?

If you only have a few settings to save, then you could save them to the standard WordPress options table. If you need to perform complex operations or complex settings it’s better to create your own tables (will discuss this in a future tutorial).

Creating the form

Let’s create a regular form and add it to the admin page we have created in this tutorial – the empty page code looks like this:

<div class=”wrap”>
<h2>WPS Poll Admin</h2>
<p>Here comes the options page content</p>

Let’s replace the <p>Here comes the options page content</p> with the form that has a field for the question text and a submit button:

<form action="" method="post" id="wps_poll_question">
<h3><label>Poll question</label>
<input type="text" id="wps_poll_question" name="wps_poll_question" value="<?php echo esc_attr(get_option(‘wps_poll_question’));?>"/></h3>
<p><input type="submit" name="submit" value="Save" /></p>

Because we have a very simple form, we will save the content to the regular WordPress options table, so we can let WordPress handle to form submission process by setting the form action to options.php. The next thing to do is to handle the form sanitization.

Handing the form sanitization

The good news is that WordPress has the ability to handle the form submission sanitization, so you don’t need to code that much, just use the built in capabilities. Let’s create a function called wps_poll_start and use the register_setting WordPress function; the first parameter is the options group (so let’s name it wps_poll_options) and the second one the the options field. The options field should have the same name as the naming inside the form we have created:

function wps_poll_start () {
register_settings(‘wps_poll_options’, ‘wps_poll_question’);

You also need to add an action that will actully run the wps_poll_start function – let’s register it at the admin_init hook:


Adding the sanitization process to the form

Right now we have created the sanitization functions, the next thing to do is to add the sanitization process to the actual form. To do this, we only need to add a bit of php right at the begining of the form: <?php settings_fields(‘wps_poll_options’); ?> which basically is a call to the sanitization

Here is how all the code looks:

function wps_poll_start () {
register_settings(‘wps_poll_options’, ‘wps_poll_question’);


function wps_poll_options_page () {
<div class=”wrap”>
<h2>WPS Poll Admin</h2>
<p>Here comes the options page content</p>
<form action="options.php" method="post" id="wps_poll_question">
<?php settings_fields(‘wps_poll_options’); ?>
<h3><label>Poll question</label>
<input type="text" id="wps_poll_question" name="wps_poll_question" value="<?php echo esc_attr(get_option(‘wps_poll_question’));?>"/></h3>
<p><input type="submit" name="submit" value="Save" /></p>