使用短代码创建自定义 wordpress 插件

Creating a custom wordpress plugin with shortcode

我正在尝试创建我的第一个包含短代码的 Wordpress 插件,但我似乎无法让它工作。当我输入简码 [first] 时,它只显示“[first]”,即使它写在 post/page 中的 HTML 中。我错过了什么?

 <?php
 /*
 * Plugin Name: WordPress ShortCode
* Description: Create your WordPress shortcode.
* Version:
* Author:
 * Author URI:
*/

 function wp_first_shortcode(){
  echo "Hello World";
 }

add_shortcode(‘first’, ‘wp_first_shortcode’);
 ?>

没有错误,只是简码显示不正确。

return不要echo。来自 the add_shortcode() docs:

Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce expected side effects from the call, since you cannot control when and where they are called from.

所以:

function wp_first_shortcode(){
  return "Hello World";
}

也不要在您的代码中使用弯引号。曾经。将 add_shortcode(‘first’, ‘wp_first_shortcode’); 更改为 add_shortcode('first', 'wp_first_shortcode');

另见 https://developer.wordpress.org/plugins/shortcodes/basic-shortcodes/