【问题标题】:"hide" element when if-statement is true (similar to if > then)当 if 语句为真时 \"hide\" 元素(类似于 if > then)
【发布时间】:2022-11-02 02:23:41
【问题描述】:

我有这段代码可以在 woocommerce 中为我的产品添加自定义字段:

add_action( 'woocommerce_single_product_summary', 'shoptimizer_custom_author_field', 3 );
function shoptimizer_custom_author_field() { ?>
<?php if(get_field('author')) { ?>
<div class="cg-author"><?php the_field('author'); ?></div>
<?php }
}

现在我想在 if 语句中添加一个条件,即“如果字段不为空,则隐藏产品标题”。

产品页面产品标题的类似乎是“product_title”。

一旦将它添加到上面的这段代码中,这将是多么令人着迷。我认为这没什么大不了的,但遗憾的是我的理解以 HTML 和 CSS 结束。

【问题讨论】:

    标签: php wordpress if-statement woocommerce hide


    【解决方案1】:

    我不确定我是否正确理解了您的问题,但是如果您想在自定义字段不为空的情况下隐藏产品标题,您可以使用以下代码:

    add_action('woocommerce_single_product_summary', 'shoptimizer_custom_author_field', 3);
    
    function shoptimizer_custom_author_field() {
        if (get_field('author')) {
            echo '<style>.product_title { display: none; }</style>';
        }
    }
    

    如果要在自定义字段为空的情况下隐藏产品标题,可以使用以下代码:

    add_action('woocommerce_single_product_summary', 'shoptimizer_custom_author_field', 3);
    
    function shoptimizer_custom_author_field() {
        if ( ! get_field('author')) {
            echo '<style>.product_title { display: none; }</style>';
        }
    }
    

    【讨论】:

    • 谢谢二涵的回答!您的代码中似乎删除了以下行: <div class="cg-author"><?php the_field('author'); ?></div> 没有这个自定义字段将不会像看起来那样显示。此外,您的编辑似乎缺少 ?php 部分。您能否以某种方式将您的 display: none 方法与上面的完整代码一起使用?因为我认为它会起作用!对我来说很难做到这一点,因为我很遗憾对规则一无所知。 :-) 希望收到您的回信,再次感谢!
    • 还!是的!当自定义字段不为空时,我想隐藏产品标题
    【解决方案2】:

    只是为了结束这个线程,任何寻求类似答案的人都可以复制并粘贴对我有用的解决方案:

    add_action( 'wp_head', function() {
    
        ?><style>
        h1.product_title.entry-title {
        display: none;
    }
    
    .cg-title h1.product_title.entry-title {
        display: block !important;
    }
        }</style><?php
        
    } );
    
    
    add_action( 'woocommerce_single_product_summary', 'shoptimizer_custom_author_field', 3 );
      
    function shoptimizer_custom_author_field() { ?>
    
    <?php if(get_field('author')) { ?>
        
        <div class="cg-author"><h1><?php the_field('author'); ?></h1></div>
    <?php }
    else {?>
    <div class="cg-title"><?php woocommerce_template_single_title(); ?> </div> 
    <?php   
        }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多