无法获取WordPress短代码来显示文件内容

时间:2014-04-16 15:06:34

标签: php wordpress shortcode

我正在尝试创建一个简单的插件来运行脚本并使用短代码显示关联的html表单。我注册脚本没有问题,但无法获取短代码来显示文件内容。这就是我所拥有的:

/* 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');

谢谢!

1 个答案:

答案 0 :(得分:1)

短代码功能缺少返回值。你一气呵成,但我按照以下方式分解:

  • plugins_url()通常使用/internal-path/file.ext__FILE__构建,用于获取我们的插件文件夹名称。

  • 非常适合使用wp_remote_get()来测试is_wp_error()是否真的有效。

  • 您可能只是将它用于测试,但尝试始终为您的功能提供唯一的名称

最终代码:

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;
}