WordPress短码函数 - 返回替换回波



我正在尝试在我的WordPress博客中创建一个带有Google Plus评论的框。我的博客于2016年1月从HTTP迁移到HTTP,因此,如果迁移日之前的帖子日期,我想用不同的永久链接来调用评论框。

这是原始的G 评论框:

<div class="g-comments"
    data-href="<?php the_permalink(); ?>"
    data-width="700"
    data-first_party_property="BLOGGER"
    data-view_type="FILTERED_POSTMOD">
</div>

我正在使用Studiopress Genesis,在用Genesis Simple Hooks注释原始WP注释之前,G 代码放在循环中。这就是我写的,它出现在内容之前。我该如何从回声返回?有宝贵的帮助吗?

<?php
$permalink = get_permalink();
$now = time();
$compare_time = mktime(0, 0, 0, 1, 1, 2016);
$post_time = get_post_time('U');
$url03 = str_replace('https://', 'http://', $permalink );
if ($post_time < $compare_time) {
echo '<div class="g-comments" data-href="';
echo $url03 . '"';
echo ' data-width="700" ';
echo 'data-first_party_property="BLOGGER" ';
echo 'data-view_type="FILTERED_POSTMOD">';
echo '</div> ';
}
else {
echo '<div class="g-comments" data-href="';
echo the_permalink() . '"';
echo ' data-width="700" ';
echo 'data-first_party_property="BLOGGER" ';
echo 'data-view_type="FILTERED_POSTMOD">';
echo '</div> ';
}
?>

您只需要将HTML字符串保存到变量并返回该变量即可。像这样的事情应该起作用。

<?php
function google_comments_html() {
  $permalink = get_permalink();
  $compare_time = mktime(0, 0, 0, 1, 1, 2016);
  $post_time = get_post_time('U');
  if ($post_time < $compare_time) {
    $permalink = str_replace('https://', 'http://', $permalink );
  }
  $html = <<<HTML
    <div class="g-comments"
      data-href="$permalink"
      data-width="700"
      data-first_party_property="BLOGGER"
      data-view_type="FILTERED_POSTMOD">
    </div>
HTML;
  return $html;
}
// Example calling the method
echo google_comments_html();

请注意,末端HTML;不能在其左侧任何空间。

只需使用ob_get_contents:http://php.net/manual/enual/en/function.ob-get-contents.php

ob_start();
$permalink = get_permalink();
$now = time();
$compare_time = mktime(0, 0, 0, 1, 1, 2016);
$post_time = get_post_time('U');
$url03 = str_replace('https://', 'http://', $permalink );
if ($post_time < $compare_time) {
echo '<div class="g-comments" data-href="';
echo $url03 . '"';
echo ' data-width="700" ';
echo 'data-first_party_property="BLOGGER" ';
echo 'data-view_type="FILTERED_POSTMOD">';
echo '</div> ';
}
else {
echo '<div class="g-comments" data-href="';
echo the_permalink() . '"';
echo ' data-width="700" ';
echo 'data-first_party_property="BLOGGER" ';
echo 'data-view_type="FILTERED_POSTMOD">';
echo '</div> ';
}
$out = ob_get_contents();
ob_end_clean();
return $out;

最新更新