Display random posts in WordPress

WordPress posts may be randomly displayed using the “Get random results from a MySql table” tip placed in a simple plugin.

What this plugin does is to simply add the “RAND()” value to “ORDER BY” clause in the sql query which retrieves the WordPress posts.

In order to use the plugin, just place the above code in a file, upload it to your WordPress plugins directory and activate it. If you use cache related plugins it may be necessary to disable them to view the randomized posts.

Get random results from a MySql table

It is possible to retrieve random results from a MySql table using the RAND() mathematical function.

In order to get the random results, the RAND() function should be used in the ORDER BY clause, like in the example below:

Retrieving random results directly from MySql is useful since you don’t need another step in your application in order to manually randomize the sql results. For example if the sql results are retrieved without being randomized you need to use a “shuffle” like function to get random results in PHP.

Insert value “0” for primary keys with auto increment in MySQL

In order to insert value 0 in a field that is set as primary key for a MySQL table you need to execute the following query prior to any insert query:

Now you can successfully run the insert query with 0 set as value for a primary key, without getting any error message.

Mentioning the “SESSION” variable will make sure that you do not change the sql mode globally, but if you really want to change it globally you need to execute:

 

Disable foreign key checks in MySQL

Disabling foreign key checks in MySQL is usefull when you are dealing with tables that use foreign keys (InnoDB engine).

You can not delete (drop) multiple tables, a parent table or a child table until you disable foreign key checks four your current database.

The sql command to disable foreign key checks is:

SET FOREIGN_KEY_CHECKS = 0;

To  enable the foreign key checks use the opposite command:

SET FOREIGN_KEY_CHECKS = 1;