dongshi7433 2018-11-08 11:52
浏览 41
已采纳

如果项目计数大于4,Wordpress将显示短代码

I am using a plugin (developed by someone else) which is outputting a shortcode [wof_wheel id="1111"]. I am using this shortcode on a page.

I am trying to apply conditional logic to the shortcode to only display/run the shortcode IF the number of items in the cart is greater than 4.

I know how to get and then check the cart item count with WC()->cart->get_cart_contents_count() but not sure if its possible to implement the shortcode display/run logic.

function do_shortcode() {     

$items_count = WC()->cart->get_cart_contents_count();

        if ($items_count > 4) {
DISPLAY/RUN SHORTCODE
} else if ($items_count < 4) 
    {
DO NOT DISPLAY/RUN SHORTCODE
}
}

Is this type of conditional logic possible with shortcodes?

  • 写回答

3条回答 默认 最新

  • doucong3048 2018-11-08 15:18
    关注

    What @LoicTheAztec is one good solution but if you want another solution you can use the following:

    WordPress have built in function which allow you to remove the default callback function for your shortcode and replaced it with your custom one.

    In this case we are going to check if the cart content count is more than 4 then remove the default callback and replace it with ours .

    i will consider for example that the page id which you have is 49 here which you should change when using this code to match the page which contain the shortcode.

    //Our Check 
    function checkShortCode()
    {
        $page = get_post(49);
        if (WC()->cart) {
            $items_count = WC()->cart->get_cart_contents_count();
    
    
            if ($items_count == 4) {
                //Remove the Default Hook function for this shortcode
                remove_shortcode('wof_wheel');
                //Add custom callback for that short to display whatever message you want
                add_shortcode('wof_wheel', 'myCustomCallBack');
            }
        }
    }
    add_action('wp_loaded', 'checkShortCode');
    

    now we need to add our custom callback to display whatever message you want:

    function myCustomCallBack()
    {
        echo 'my shortcode is running';
    }
    

    the code above is tested and working 100%

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配