How can I execute some small piece of PHP code in a sandbox area of my WP?

I’d like to execute some small piece of code like the following one:

global $wpdb;
$rows = $wpdb->query('SELECT DATE(post_date) AS date, COUNT(*) AS count FROM ' . $wpdb->posts . ' GROUP BY DATE(post_date) ORDER BY DATE(post_date)');
foreach ($rows as $row) {
    echo $row->date . ': ' . $row->count . '<br>';

But I don’t want to write a plugin for this small task. How can I manage it?

Solutions Collecting From Web of "How can I execute some small piece of PHP code in a sandbox area of my WP?"

Best way for execute any PHP code during development its Console from Developer plugin. You can install Developer plugin, and activate console module. “Debug” link will appear in top right corner in your admin bar. You can go there, and execute any php code you like.

Context is everything with a question like this. However, since you are talking about a “sandbox” I am going to assume this is thowaway install on a development server and you just want to test bits and pieces of code without much hassle. To do that…

  1. I usually drop code into a mu-plugin file– create a directory in
    wp-content called mu-plugins. Every file in that directory will
    execute automatically.
  2. Or just hack the code into the theme where ever needed. I stress the
    assumption about the “throwaway” install. This is for short term
    testing only– for example, testing code for these question. I do
    not expect to keep it, nor deploy it. When WordPress is updated, it
    all gets overwritten. This kind of piecemeal code testing is the only time I’d advocate hacking Core.

Just edit functions.php file in theme’s directory which is active and write this somewhere to the end of the file:

function prefix_my_dump() {
    //paste your code here
add_action( 'wp_footer', 'prefix_my_dump' );

That hook ‘wp_footer’ will be echoing the content somewhere to the end of the page. You can use an other action of course. Check this page for some used actions & filters:

A relatively safe way to do it on even a production site is to make a new page and set it to private then copy the page.php file in your theme and change the title of that file to page-new_page_id.php (replace new_page_id with the id or name of the new page you created) then put your code into the content area of the new page-new_page_id.php file and access it as a logged in user.

Setting the new page to private will make it visible only to logged in users, so it is “relatively” safe to do even on a live site.