【问题标题】:How to fix the problem with the_content filter如何解决 the_content 过滤器的问题
【发布时间】:2019-01-05 23:56:38
【问题描述】:

我想在 the_content 之后添加包含我的自定义帖子信息的短代码,但是当我添加它在 the_content 之前显示的代码时

这是我的代码

<?php

function foobar_func() { ?>

  <h3>Title : </h3>
  <ul>
    <li>foo : </li>
  </ul>

<?php }

add_shortcode( 'project_information', 'foobar_func' );

function wpdev_before_after( $content ) {

  $beforecontent = '';
  if ( is_single() ) {
    $aftercontent = '[project_information]';
  } else {
    $aftercontent = '';
  }
  $fullcontent = $beforecontent . $content . $aftercontent;

  return $fullcontent;

}

add_filter('the_content', 'wpdev_before_after');

?>

我的 foobar_func 应该是这样的,并且我有更多的自定义分类要列出,如果我使用变量来显示它们,我的代码将非常混乱

function foobar_func() { ?>

  <h3>Title : </h3>
  <ul>
    <li>foo : <?php

    $terms = wp_get_post_terms( $post->ID, 'taxonomy', $args );
    foreach( $terms as $term ) {

      if ( end($terms) == $term ){
        echo '<a href="' . esc_url( get_term_link( $term ) ) . '" title="' . esc_attr( sprintf( __( '%s', 'tiads' ), $term->name ) ) . '">' . $term->name . '</a>';
      } else {
        echo '<a href="' . esc_url( get_term_link( $term ) ) . '" title="' . esc_attr( sprintf( __( '%s', 'tiads' ), $term->name ) ) . '">' . $term->name . '</a> , ';
      }

    }

    ?></li>
  </ul>

<?php }

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    尝试将 html 分配给变量并将其返回到您的 foobar_func()

    function foobar_func() { 
      $html = "  
      <h3>Title : </h3>
      <ul>
        <li>foo : 
        ";
        $terms = wp_get_post_terms( $post->ID, 'taxonomy', $args );
        foreach( $terms as $term ) {
    
          if ( end($terms) == $term ){
            $html .= '<a href="' . esc_url( get_term_link( $term ) ) . '" title="' . esc_attr( sprintf( __( '%s', 'tiads' ), $term->name ) ) . '">' . $term->name . '</a>';
          } else {
            $html .= '<a href="' . esc_url( get_term_link( $term ) ) . '" title="' . esc_attr( sprintf( __( '%s', 'tiads' ), $term->name ) ) . '">' . $term->name . '</a> , ';
          }
    
        }
        $html .= "
        </li>
      </ul>";
      return $html;
    }
    

    【讨论】:

    • 我无法将它们存储在变量中,因为我需要在我的简码中使用一些查询
    • 即使您需要运行查询和输入数据,您应该仍然能够返回变量吗?你能准确地发布你的代码吗?
    • 查看我更新的答案,这将提供与之前完全相同的结果,但放入变量中。
    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 2013-01-19
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2020-01-01
    相关资源
    最近更新 更多