How To Properly Create Tables In WordPress Multisite Plugins

Recently, I added full WordPress Multisite compatibility to my Email Log WordPress plugin and during the process, I learned a lot about how to create and handle tables in WordPress Multisite plugins. I thought of documenting it here so that it would be useful for other plugin authors.

Creating tables in Single site installations

Before we get into WordPress Multisite, first let’s see how we can create a table in a single site WordPress installation. You have to hook into the register_activation_hook action, which will be called every time you activate your plugin and then check if your table exists or not. If it doesn’t exist, then you can create your table.

The following code shows how you can do it.

The above code will work even in WordPress Multisite installations, if your plugin will be activated individually for each blog. But if your plugin is networked activated, then the above code will create the table only for the primary blog.

Creating tables for all blogs in a WordPress Multisite installation

Now that we know how to create the table for a single blog, let’s see how we can create the table for all the blogs in a WordPress Multisite installation. Even in this case, we have to hook into the same register_activation_hook action, but should loop through all the blogs in the network.

The following code shows how you can do it.

Creating table when a new blog is created

The above code will create the table only for the blogs that were created before the plugin got network activated. We should also make sure that we create the table for every new that gets created. In order to do that we can hook into the wpmu_new_blog action.

The following code shows how you can do it.

Deleting the table when a blog is deleted

Now that we are creating the table for every new blog, it is our job to make sure that the table is deleted when the blog is deleted. In order to do that, we can hook into the wpmu_drop_tables filter.

The following code shows how you can do it.

Querying the correct table

When we are querying the table, we should always use $wpdb->prefix . $table_name. If we do that, then WordPress will automatically query the correct table based on the current blog. We don’t have to manually find out the blog id and add it to the table name.

Now your plugin should be completely compatible with WordPress Multisite 🙂

Alternate approach

If you look into the above code closely, you will notice that we are creating one table for each blog in the network. For most WordPress Multisite installations, this shouldn’t be a problem. But some WordPress Multisite installation may have thousands and even hundreds of thousands of blogs. In those cases, we might end up creating huge amount tables which might become a bottleneck. Also my plugin needed just one table. Some plugins might need more than one table, which might also increase the number of tables that gets created.

One alternate approach is to create just one table for all blogs and then separate out data for each blog using a blog_id column. While querying the table, we can filter out based the blog_id column.

If I had started my plugin from scratch, I would have done that instead of creating separate tables.

Update: As Damian pointed out below in the comments, if you are using this approach, then you used use $wpdb->base_prefix to get the main prefix and not the individual sites prefix.

Removing the tables when the plugin is deleted

The other thing to keep in mind is that we should delete all the tables when the plugin is deactivated and deleted. I will write a separate article explaining how we should do that.

With WordPress Multisite becoming more popular these days, I hope this information was useful to you. Do let me know if you have any question or comments. Also you can checkout the entire code of my Email Log plugin in github.

Posted in WordPress | Tagged , , , | 20 Comments

Email Log plugin is now fully WordPress Multisite compatible

I just released version 1.7 of my Email Log WordPress plugin, which adds full compatibility with WordPress Multisite.

About Email Log WordPress plugin

Email Log is a WordPress plugin that allows you to log every email sent through WordPress and provides a UI where you can view them. The logged emails can be searched based on date, email address or subject.

WordPress Multisite compatibility

Earlier versions of Email Log plugin had some compatibility with WordPress Mu (older version of multisite), but I didn’t test it for long time. Also when WordPress Mu got merged into WordPress core, certain things have changed and my plugin was not fully compatible after that.

I came to know about it recently and then started to work on it to make it fully compatible with WordPress Multisite, since I have moved this blog to WordPress Multisite as well. I also learned a lot about WordPress Multisite during the process and will write a separate blog article about it soon. Update: As promised, here is the new blog article explaining how to properly create tables in WordPress Multisite plugins.

Dev Time

This release took me about 2.5 hours of development time. You can find more details about the dev time tracking which I have recently started doing in a separate blog post.

Download

You can download the latest version of the Plugin from the Plugin’s home page.

Feedback

Try out the Plugin and if you have any comments or if you want to report any bugs, please leave a comment below.

Posted in Plugin Releases | Tagged , , , , | 1 Comment

Prevent users from adding new terms to custom taxonomy in WordPress

Recently I faced a scenario where I had to prevent certain users from adding new terms to some custom taxonomies that I created. After some research I found that there isn’t a straight forward way to do this using user capabilities or roles.

The only way is to use the pre_insert_term hook and black-list taxonomies based on user capabilities. I am sharing the code here so that it would be useful for people who want to something similar.

In the above code change the taxonomy name and capability to suit your usecase.

Posted in WordPress | Tagged , | 8 Comments

Merged my blogs using WordPress Multisite

Most of you know that I have another website in addition to this one where I talk about my experience with hardware programming. When I started the website in late 2012, I decided to host it using another single instance of WordPress.

Recently one of the users of my Bulk Delete WordPress plugin asked me if I can add the ability to delete posts in bulk from multiple sites at once in a WordPress multisite installation. I have played around with WordPress MU a bit before it got merged with WordPress, but haven’t played much with WordPress multisite after it got merged. I did a WordPress multisite installation in my dev server and was very impressed with it. I also realized that it will save me lot of time by just maintaining one WordPress installation instead of two.

After testing out plugin compatibility, I converted both the blogs into a single WordPress multisite installation. The migration process was very simple and now both the sites are powered by a single WordPress multisite installation.

If you manage more than one WordPress installation, then do consider doing it using WordPress multisite. It might simplify lot of things for you.

Posted in WordPress | Tagged , , | 2 Comments

Looking back at 2013

Another year just ended and it’s time for publishing my year end review like the ones I did for the previous few years.

Personal Highlights

2013 was a milestone year for me in the personal front. I spawned a new process 😉 (Translation for those who didn’t get it: I became a dad).

Like all parents know, this is the most rewarding as well as the most demanding experience. Luckily, my little one has kind of gotten into a proper sleeping schedule these days and so my (and my wife) zombie days are in the past.

This would explain why I was kind of out of action (less blog posts, not much public speaking etc) in the last few months. Hopefully, I should be back to action in 2014.

Open source contribution

Back in the early days of 2013, I decided to do at least one contribution per day to open source projects. I was able to maintain this streak for more than 4 months (124 days to be exact). A look at my github profile, should explain everything 🙂

I also took over the Arduino Makefile project and worked hard to steadily increase its popularity. Right now it has around 250 stars and close to 100 forks in Github.

I also moved most of my WordPress plugins to github. This also increase the popularity of my WordPress plugins and also user contributions.

Reading

Towards the end of the year, I decided to take a reading break and this helped me to complete around 10 novels from Isaac Asimov’s famous Foundation Series.

Blog Stats

I used my Year End stats WordPress plugin to generate the following stats.

2013-no-posts2013-no-comments2013-total-post-length 2013-avg-post-length

The total number of posts that I have written in 2013 has increase a little bit and I am happy about it.

I am planning to write a little more in 2014 as well. Hopefully my little one allows me to do so 😉

What’s in for 2014?

I am definitely planning to spend quality time with my family, especially the little one 🙂 As most parents know, the first few years of a kid are the most rewarding ones and I don’t want to miss out on it.

Assuming that I will have time after that, I want to do the following as well.

Books

I definitely want to complete the Foundation Series that I started. I still have another 5 books to complete.

After that I am planning to read favorite person Chris Hadfield’s Autobiography: An Astronaut’s Guide to Life on Earth. I already have the book, I am just waiting to finish Foundation Series.

Also, if you have recommendation, please let me know. I am planning to read at least a dozen books this year.

Learn R

I am also planning to concentrate a little bit more on Statistic and Machine Learning and as part of it, I am planning to learn R. I am also planning to see if I compete on some competitions in Kaggle. I might also start writing about more about Machine Learning this year. So stay tuned 🙂

Hardwarefun

Regarding hardware stuff, I am planning expand HardwareFun.com and write more posts there and also continue working on Arduino and start playing around with Raspberry Pi as well. So it is going to be pretty exciting.

From the looks of it, 2014 seems to be an exciting as well as a busy year and I am really looking forward to it.

So how was your 2013?

Posted in Random/Personal | Tagged , , , | Leave a comment

Get the SQL query generated by WordPress

One of the good things about WordPress is that it provides a nice abstraction to DB and you can query pretty much anything from the DB, by using the appropriate functions instead of writing the query yourself.

All though it is good, there are times when you want to see what was the actual SQL query that got generated. I faced this senarious myself, when I was debugging an issue in my Bulk Delete WordPress plugin.

It turns out that it is quite easy to do it.

The WP_Query object has a method called request that returns the SQL query that was generated.

So if you want to get the query generated by the global $wpdb object then you can use the following code

<?php echo $GLOBALS['wp_query']->request; ?>

On the other hand, if you are using a custom WP_Query object then you can call the request method on your object.

<?php
$my_query = new WP_Query();
echo $my_Query->request;
?>

Posted in WordPress | Tagged , , | 1 Comment

Error while starting Jython in Mac

After I figured out how I can use Python to create Pig UDF functions, I got interested in Jython and wanted to play around with it. So I installed it in my Mac through homebrew by executing the following command.

brew install jython

Everything got installed properly, I was able to run Jython after setting
up the following lines in my [bashrc](https://github.com/sudar/dotfiles)

export JYTHON_HOME=$(brew --prefix jython)/libexec
export PATH=$PATH:$JYTHON_HOME/bin

But there was one small annoyance. Every time I was staring Jython, I was getting the following strange warning.

expr: syntax error

After a couple of web searches, I stumbled upon an email thread in the Jython-users mailing list. Basically it was due to a bug in the bash script that is used to start Jython. I opened /usr/local/Cellar/jython/2.5.3/libexec/bin/jython file and changed the line, which fixed the error.

if expr "$link" : '/' > /dev/null; then to if expr "$link" : '[/]' > /dev/null; then

I am exploring Jython more and will keep you guys updated, if I find something interesting.

Posted in Python | Tagged , , , | 1 Comment

Spawned a new process ;)

Well, I wanted to have the geekiest synonym for “We just had a baby” as the title for this post (similar to my wedding card). Since I am currently typing this from a hospital, sleep-deprived, while constantly sifting my attention between my recovering wife and my new born child, this is the best I came up with 😉

In the last 24 hours, I have experienced extreme cases of all the 8 emotions specified in Robert Plutchik’s theory, but in spite of it this had been the best 24 hours in my entire life so far 🙂

So guys, join me in welcoming our son to this beautiful world. By the way, all credit for the creation of this new process goes to my wife who did all the real work 😉

More details and pics coming soon, after (if) I catch up with some sleep 🙂

Posted in Random/Personal | Tagged , | 11 Comments

Isaac Asimov Foundation Series reading order

Last week, I asked for recommendations for some SciFi/Fantasy books and the response was enormous. Thanks to everyone who gave me recommendations. After some careful analysis, I finally decided to read Foundation Series by Isaac Asimov.

I was reading the wikipedia article of Foundation Series and then realized that the books were not published in chronological order, which bought the question – In which order should I read the books? In chronological order or published order.

After some research I came to know that Isaac Asimov himself suggested (In the Author’s note at the beginning of Prelude to Foundation) to read the books in chronological order. So I decided to follow his advice 🙂

I am currently reading them in the following order. The year in the bracket is the year of publication.

  • I, Robot (1950)
  • The Caves of Steel (1954)
  • The Naked Sun (1957)
  • The Robots of Dawn (1983)
  • Robots and Empire (1985)
  • The Currents of Space (1952)
  • The Stars, Like Dust (1951)
  • Pebble in the Sky (1950)
  • Prelude to Foundation (1988)
  • Forward the Foundation (1992)
  • Foundation (1951)
  • Foundation and Empire (1952)
  • Second Foundation (1953)
  • Foundation’s Edge (1982)
  • Foundation and Earth (1986)

I have already finished the first two and I am currently reading “The Naked Sun”. So far it’s been really excellent and once again thanks everyone for the recommendation.

Posted in Books | Tagged , | 1 Comment

Seeking recommendation for some Fantasy/Sci-Fi/Fiction books

It’s been quite sometime since I read anything substantial and so I am planning to take a “reading break” and want to dedicate my free time in the next couple of months for reading.

Since I have a couple of months for this, I don’t want to read short stories or a single novel. Instead, I want to read a series so that once the characters are introduced, they will continue to be present for most of the series. This will be an important factor for me, since it motivates me to complete all the books in the series. This is one of the reason, why I was able to complete the entire Sherlock Holmes series in less than a week 🙂

I am not very particular about the genre very much, but I would prefer either Fantasy or Sci-Fi. The series that immediately came to my mind were Harry Potter and The Lord of the Rings. I posted about it today morning in Twitter and asked for recommendations.

Within a few minutes, I got the following good suggestions and now I have the tough job of picking it up from here 😉

I have not made up my mind yet, but I am leaning towards Foundation series by Isaac Asimov.

Meanwhile, if you guys have any more suggestions, kindly do let me know.

Update: I have decided to take up Foundation Series by Isaac Asimov first. Thanks everyone for the recommendations.

Posted in Books | Tagged , | 6 Comments