如何为您在 WordPress 中创建的每个自定义帖子类型保存短代码

问题描述 投票:0回答:1

基本上我想做的是为我在 WordPress 插件中创建的每个 cpt(自定义帖子类型)创建一个简码,但我不明白为什么当我使用简码时它会返回代码本身,就像我使用 [ my_shortcode_324] 它返回相同的东西

if ( ! class_exists('My_Plugin_Shortcode') ){

    class My_Plugin_Shortcode{
        public $cptID;
        public function __construct($cptID){
            $this->cptID = $cptID;
            add_shortcode('my_plugin_'.$this->cptID, array($this, 'add_special_shortcode'));
        }

        public function add_special_shortcode($atts = array(), $content = null, $tag = ''){
            $atts = array_change_key_case( (array) $atts, CASE_LOWER);
            $cptID = $this->cptID;
            extract( shortcode_atts(
                array(
                    'id' => $cptID,
                    'orderby' => 'date'
                ),
                $atts,
                $tag
            ));
            ob_start();
            require( MY_PLUGIN_PATH . 'views/my-plugin_shortcode.php');
            return ob_get_clean();
        }
    }
}

以及保存方法上的自定义帖子类:

public function save_post( $post_id ){
            if ( isset( $_POST['my_plugin_nonce'] )){
                if ( !wp_verify_nonce( $_POST['my_plugin_nonce'], 'my_plugin_nonce' )){
                    return;
                }
            }
            if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE){
                return;
            }
             // Instantiate the My_Plugin_Shortcode class when saving the CPT
            $my_plugin_shortcode = new My_Plugin_Shortcode($post_id);
        }
wordpress plugins shortcode
1个回答
0
投票

您面临的问题可能是由于您正在“save_post”方法中创建“My_Plugin_Shortcode”类的实例,这可能不是短代码注册的理想位置。短代码通常在 WordPress 初始化期间注册。

要解决此问题,您应该将“My_Plugin_Shortcode”类的实例化移动到更合适的挂钩,例如“init”。

这样,短代码将被正确注册,并且当您在内容中使用它时应该按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.