How to access WordPress functions in external file

WordPress functions are very useful and solve lots of purposes. But normally, we can access it only inside the wordpress files like themes, plugins etc.

Wouldn’t it be great if we can access these in other files also that are not the part of usual wordpress file structure.

Then, you will be happy to know that we can easily do it. All we need to do is just include the wp-load.php file at the starting of our external php file.

Suppose, if your file is in the root directory (test.php). Then, you just have to add the following line of code on top.

<?php
    //Include the wp-load.php file
    include('wp-load.php');
    //As this is external file, we aren't using the WP theme here. So setting this as false
    define('WP_USE_THEMES', false);
    //Optional, adding the WP blog header which will include the wordpress head in the file
    require('wp-blog-header.php');
    // Edit your code below
    if(is_user_logged_in() ) {
        $user = wp_get_current_user();
        $role = (array) $user->roles;
        echo "role is ".$role[0];
    }
?>

Now, you can access any wordpress function in your file.

Leave a Reply

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