【问题标题】:Syntax for conditional statement in Wordpress functions.phpWordpress functions.php 中条件语句的语法
【发布时间】:2019-01-07 16:24:35
【问题描述】:

我的知识非常有限,但我设法在自定义 functions.php 文件中添加了一个过滤器,以在发布内容之前显示一些自定义字段短代码:

//Insert custom event fields at the beginning of post content
    function custom_event($content) {
    $beforecontent = '<strong>[acf field="date"] [acf field="time"] [acf field="location" ] </strong>';
    $fullcontent = $beforecontent . $content;
    return $fullcontent;
}
add_filter('the_content', 'custom_event');

如果我想以帖子属于特定类别为条件,任何人都可以帮助我使用正确的语法吗?我想我可以使用 in_category('x') 函数,我只是不确定语法。我最终想在变量之间添加一些文本,以便显示

[日期] [时间] [地点]

适用于“活动”类别中的帖子。

感谢期待。

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    这是一个起点。

    function custom_event($content) {
        global $post;
    
        if( in_category( 'category-name-slug-id', $post ) ) {
            $beforecontent = '<strong>[acf field="date"] [acf field="time"] [acf field="location" ] </strong>';
            $fullcontent = $beforecontent . $content;
            return $fullcontent;
        }
    
        return $content;
    
    }
    
    add_filter('the_content', 'custom_event');
    

    【讨论】:

    • 完美,谢谢安德鲁。我在简码之间添加了文本,它完全符合我的要求!再次感谢。
    • 如果可以的话,还有一个问题。我将 $beforecontent 变量更改为: $beforecontent = '[ On [acf field="date"] at [acf field="time"] at [acf field="location" ]] ';如何使 on/at/at 文本标签有条件,以便它们仅在变量不为空白时显示,例如,如果没有时间或位置,它只输出:“[ On [date]]” 也可以使用调用简码get_field("acf field") 函数,如果有帮助的话。谢谢。
    • 检查短代码是否返回空字符串。您可以通过执行短代码来检查它的值,使用函数 do_shortcode() developer.wordpress.org/reference/functions/do_shortcode 存储它的输出
    • 谢谢 Andrew,这看起来像是我需要的,但我将如何将它用于我的目的?
    • 阅读函数并尝试自己编写代码,否则您将无法从本练习中学到任何东西。我已经为你提供了解决方案,现在由你来决定是否尝试一下。
    【解决方案2】:

    谢谢安德鲁。经过多次谷歌搜索和反复试验,我想出了以下内容。我不认为这是一个非常优雅的解决方案,或者即使语法完全正确但它似乎工作:

    function custom_event($content) {
        global $post;
        if( get_field( "date" ) != "" || get_field( "time" ) != "" || get_field( "location" ) != "" ){ 
            $open = "&#0091;";
        }
        if( get_field( "date" ) != ""){
            $ondate = 'On '.get_field( "date" );
        }
        if( get_field( "time" ) != ""){
            $attime = 'at '.get_field( "time" );
        }
        if( get_field( "location" ) != ""){
            $atlocation = 'at '.get_field( "location" );
        }
        if( get_field( "date" ) != "" || get_field( "time" ) != "" || get_field( "location" ) != "" ){ 
            $close = "&#0093; ";
        }
        if( in_category( 'events', $post ) ) {
            $beforecontent = "<strong>$open$ondate $attime $atlocation$close</strong><br><br>";
            $fullcontent = $beforecontent . $content;
            return $fullcontent;
        }
        return $content;
    }
    add_filter('the_content', 'custom_event');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-16
      • 2012-12-01
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多