Wordpress shortcode is not called

醉酒当歌 提交于 2021-01-29 17:59:38

问题


Okay, I have created a plugin and now want to provide shortcode to app.
Here is my only file in wp-content/plugins/my-plugin/my-plugin.php

<?php
/**
 * Plugin Name: Latest Issue
 * Author: Max Tsepkov
 * Author URI: http://www.yogi.pw
 */

add_action('init', function() {
    add_shortcode('my-plugin', function() {
        // ... my code

        return 'string';
    });
});

I know that plugin is activated and the callback for init is called.
But the shortcode function is never get called.
I add text [my-plugin] to a widget, and it isn't replaced as well.

What do I do wrong? How to correctly register a shortcode?


回答1:


I guess you PHP is at least 5.3, so you can make it work in a widget, you need to add this code.

add_filter('widget_text', 'do_shortcode');

I tested your code and it works.




回答2:


Turned out, that some themes are not parsing shortcodes in widgets.
We can explicitly hook into theme filter and let it run shortcodes in widgets.
For details see https://wordpress.org/support/topic/how-to-make-shortcodes-work-in-a-widget

And there is no need for hook into init action. This code works:

<?php
/**
 * Plugin Name: Latest Issue
 * Author: Max Tsepkov
 * Author URI: http://www.yogi.pw
 */

// Allow theme to parse shortcodes in widgets
add_filter('widget_text', 'do_shortcode');

add_shortcode('my-plugin', function() {
    // ... my code

    return 'string';
});


来源:https://stackoverflow.com/questions/25933299/wordpress-shortcode-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!