pfbarnet
pfbarnet

Reputation: 111

Creating a custom wordpress plugin with shortcode

I'm trying to create my first Wordpress plugin that includes a shortcode and I can't seem to get it to work. When I type my shortcode [first] it just displays "[first]" even though it's written in HTML in the post/page. What am I missing?

 <?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’);
 ?>

There are no errors, just shortcode is not displaying properly.

Upvotes: 0

Views: 1286

Answers (1)

j08691
j08691

Reputation: 207861

return don't echo. From 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.

So:

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

Also don't use curly quotes in your code. Ever. Change add_shortcode(‘first’, ‘wp_first_shortcode’); to add_shortcode('first', 'wp_first_shortcode');

See also https://developer.wordpress.org/plugins/shortcodes/basic-shortcodes/

Upvotes: 2

Related Questions