Testing WordPress functions in the CLI

Sometimes you need to test some code, API functions,… in a WordPress plugin or theme without using anything else.

To do this, you can use the WP-CLI. Make sure you have installed it.

To open an interactive shell with WordPress loaded, where you will have access to all the functions, classes and globals that you can use within a WordPress plugin, you have to execute:

wp shell

Inside the shell, you can write PHP code to test. E.gr., you can test the get_current_blog_id() function, that retrieves the current site ID.

wp> echo get_current_blog_id();
1

To show the users, you can execute this code:

wp> $users = get_users();
wp> foreach ( $users as $user ) \
    { \
        echo $user->user_nicename . PHP_EOL; \
    }

The “\” symbol is used in the CLI to split the code between different lines.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.