【问题标题】:Using a WP filter makes a value disappear?使用 WP 过滤器会使值消失?
【发布时间】:2016-10-29 13:16:49
【问题描述】:

我正在使用this 来显示一些推文。

使用here 所示的覆盖过滤器后,它会使自然发生的时间戳消失。

作者给我们提供了一个示例,您可以使用它来覆盖默认标记,如下所示:

add_filter('latest_tweets_render_tweet', function( $html, $date, $link, array $tweet ){
    $pic = $tweet['user']['profile_image_url_https'];
    return '<p class="my-tweet"><img src="'.$pic.'"/>'.$html.'</p><p class="my-date"><a href="'.$link.'">'.$date.'</a></p>';
}, 10, 4 );

这是我的版本:

add_filter('latest_tweets_render_tweet', function($html){
return
'<div class="row">
    <div class="small-1 columns twitter-icon-wrap">
      <i class="fa fa-twitter tweet-icon fa-2x fa-pull-left"></i>
    </div>
  <div class="small-11 columns tweet-wrap">'.$html.'</div>
  <p class="tweet-details"><a href="" target="_blank"></a></p>
</div>';
}, 10 , 1 );

如果我在函数中的$html 变量之后添加$date,例如:

add_filter('latest_tweets_render_tweet', function($html, $date)

然后我收到警告:

Warning: Missing argument 2 for ******\******\Extras\{closure}(), called in /srv/www/*********/current/web/wp/wp-includes/plugin.php on line 235 and defined in /srv/www/*******/current/web/app/themes/*********/lib/extras.php on line 144

第 144 行是add_filter('latest_tweets_render_tweet', function($html)

如果我随后将 $date 变量添加到返回的 HTML 中而忽略警告,则会收到错误:

Notice: Undefined variable: date in.....

虽然是警告,但仍然没有显示日期。如何让日期重新出现?

【问题讨论】:

    标签: php html wordpress twitter


    【解决方案1】:

    问题是add_filter() (1) 中的最后一个参数。这个参数是number of accepted arguments

    add_filter ( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
    

    由于要使用 2 个参数,因此需要将 add_filter() 的最后一个参数更改为 2。换句话说:

    add_filter ( 'latest_tweets_render_tweet', function( $html, $date ) {}, 10, 2 );
    

    不清楚你到底想用$date做什么......所以我只是给你一个通用的例子:

    add_filter('latest_tweets_render_tweet', function( $html, $date ){
        // $html and $date are now available to you
        return true;  // remember to return something (likely something different than this)
    }, 10, 2 );  // <-- This argument is changed to 2
    

    【讨论】:

    • 是的,我已经尝试过了,但是我收到一条错误消息,提示 $date 如上所述未定义。由于某种原因,我基本上是在尝试使用 add_filter('latest_tweets_render_tweet'); 重新出现时间戳。它会删除它。
    • @AshleyBrown 这不可能。请编辑您的问题并分享引发错误的实际代码。
    • 请分享整个过滤器。目前还不清楚您使用什么代码来产生错误。
    • 您似乎没有阅读我的全部答案。我编辑澄清。您还需要将add_filter() 的最后一个参数从10, 1 更改为10, 22 表示您的过滤器函数将接受的参数数量。
    • 默认情况下,只有第一个参数会被传递给可调用对象(如果你不使用$accepted_args,默认数字是1)。当您使用多个时,您需要明确说明。我希望这是有道理的。这是那些古老的“为什么会这样???”之一。 WordPress 的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多