【问题标题】:Disable shortcode if status of value changes?如果值的状态发生变化,禁用短代码?
【发布时间】:2018-05-16 22:52:44
【问题描述】:

希望在函数中启用或禁用短代码,具体取决于值。例如,如果有人说购买许可证密钥以在他们的网站上使用某些短代码,我希望在他们的许可证过期时禁用该短代码。我一直在处理的示例函数如下:

my_premium_shortcodes(); // Fires early in my php file

function my_premium_shortcodes(){
    $status     = get_option( 'key_status' );

    if( $status !== false && $status == 'valid' ) { 

        add_shortcode('shortcode_handle_1','shortcode_function_1');
        add_shortcode('shortcode_handle_2','shortcode_function_2');

    } else {

        remove_shortcode('shortcode_handle_1','shortcode_function_1');
        remove_shortcode('shortcode_handle_2','shortcode_function_2');
    }

}

对我的方法的任何输入或是否应该以单独的方式处理该功能将不胜感激。就目前而言,当一切都启用时,短代码正在工作,但即使在“状态”更改为“无效”后仍保持启用状态。

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    您应该在两个不同的函数中使用代码,而不是在一个函数中。请查看以下代码并在您的网站中实施。

    $status     = get_option( 'key_status' );
    
    if( $status !== false && $status == 'valid' ) {
    //add a custom shortcode 
    add_action( 'init', 'my_add_shortcodes' );
    function my_add_shortcodes() {
    add_shortcode( 'myShortcode', 'my_shortcode_function' );
    }
    else{
    //which can also remove 
    add_action( 'init', 'remove_my_shortcodes',20 );
    function remove_my_shortcodes() {
    remove_shortcode( 'myShortcode' );
    }
    

    【讨论】:

    • 你好,凯沙夫。尝试运行此代码,不幸的是,即使在值更改后,短代码似乎仍顽固地保持活动状态。甚至尝试调用'global $options;'以防万一 get_option 规则不确定在哪里看,而短代码仍然顽固地存在。
    【解决方案2】:

    只是想发布更新。我在代码中使用的以前的函数显然没有正确读取状态的值。从本质上讲,我只需要使用“if”语句并删除“else”即可。

    所以这很好,仅供参考:

    function my_premium_shortcodes(){
    $status     = get_option( 'key_status' );
    
    if( $status !== false && $status == 'valid' ) { 
    
        add_shortcode('shortcode_handle_1','shortcode_function_1');
        add_shortcode('shortcode_handle_2','shortcode_function_2');
    
     } 
    }
    

    如果“key_status”实际上正在被读取,否则短代码总是被触发。

    【讨论】:

      【解决方案3】:

      将短代码功能代码添加到function.php文件或插件文件中。

          function my_add_shortcodes() {
              // Add your code here
          }
          add_shortcode( 'myShortcode', 'my_shortcode_function' );
      

      使用以下条件在您的主题的任何文件中调用短代码。

      $status     = get_option( 'key_status' );
      if( $status !== false && $status == 'valid' ) {
          echo do_shortcode('[myShortcode]');
      }
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 2020-10-21
        • 1970-01-01
        • 2021-02-14
        • 1970-01-01
        相关资源
        最近更新 更多