Trouble getting WordPress shortcode to display contents of file

I’m trying to create a simple plugin to run a script and display associated html form using a shortcode. I’ve has no problem registering the script, but cannot get the shortcode to display the file contents. Here’s what I have:

/* Add function and shortcode */
function my_function(){
    $options = wp_remote_retrieve_body( wp_remote_get( plugins_url() . '/my_plugin/my_file.html' ) );
}
add_shortcode('my-shortcode', 'my_function');

Thanks!

Related posts

Leave a Reply

1 comment

  1. The shortcode function is missing the return value. You’re doing everything in one go, but I’d break it up as follows:

    • plugins_url() is normally built with /internal-path/file.ext, and __FILE__ that grabs our plugin folder name.

    • is nice to test if wp_remote_get() actually worked using is_wp_error().

    • you’re probably using it only for testing, but try to always give unique names to your functions

    Final code:

    add_shortcode( 'my-shortcode', 'shortcode_so_23113289' );
    
    function shortcode_so_23113289(){
        $body = '';
        $response = wp_remote_get( plugins_url( '/my_file.html', __FILE__ ) );
        if( ! is_wp_error( $response ) )
        {
            $body = wp_remote_retrieve_body( $response );
        }
        return $body;
    }