0
votes

I'm attempting to add a shortcode wordpress sites using a custom plugin. No matter how I try to register or call this, the shortcode does not seem to render.

I am using the default 2020 theme from Wordpress to test this.

This is the code that adds the shortcode:

    add_shortcode(
        'test',
        function () {
            return 'test output';
        }
    );

If I manually check this on the template:

    var_dump(shortcode_exists('test'));

the following is generated on a page load:

boolean true

However, if the following is added to the page content, it does not load:

[test]

I have also added the following to the theme functions.php

add_filter( 'widget_text', 'do_shortcode' );

However, as this is not within a widget (just post text) I did this to eliminate this possibility. It did not help.

Edit: I also added the following to the page:

    do_shortcode(['test']);

This produces the required output.

Every single tutorial does the above, pretty much verbatim. What am I missing?

To be clear: Using [test] in content to show the shortcode inside post body content is the required behaviour.

2
No. I am using do_shortcode to elimiate the possibility of a content parsing issue. I want to call this through content as per the usual method: [test] or [shortcode_name]. - elb98rm

2 Answers

1
votes

Try to change the test name, suddenly it is reserved, and secondly, print the entire shortcode

print do_shortcode('[mytest]'); // [test]

<?php
/*
Plugin Name: Test
Description: La la la fa
Version: 0.1.0
*/

function question($attrs, $content = null) {
  return '???';
}
add_shortcode('question', 'question');

add_action('init', function() {
  d(do_shortcode('Are you sure [question]'));
});

enter image description here

Methods to output content with handling of shortcodes

the_content();
get_the_content();
apply_filters('the_content', $post->post_content); 

Example:

add_action('init', function() {
  d(apply_filters('the_content', 'Are you sure [question]')); // $post->post_content
});

enter image description here

0
votes

This was a custom testing template, and the content of a post is not automatically parsed. I've actually created a huge amount of custom meta data per post that I was arranging and presenting outside of the content, so I had used the $post->post_content property.

To be clear... $post->post_content is not parsed, the_content() is.

Things now work. This is a good gotcha.