WordPress短代码功能 - 用return替换echo

时间:2016-06-22 14:21:38

标签: php wordpress google-plus shortcode genesis

我正在尝试在我的WordPress博客中创建一个包含Google Plus评论的框。我的博客在2016年1月从http迁移到https,所以如果发布日期之前的帖子日期,我想用不同的永久链接调用评论框。

这是原始的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> ';
}
?>

2 个答案:

答案 0 :(得分:0)

您只需将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;的左侧不能有空格。

答案 1 :(得分:0)

只需使用ob_get_contents:http://php.net/manual/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;
相关问题