Search code examples
phpwordpressshortcode

How to fix the problem with the_content filter


I want to add shortcode that has information about my custom post after the_content but when i add the code it shown before the_content

Here is my code

<?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');

?>

My foobar_func should be like this and i have more custom taxonomy to list and if I use variable to show them my code will be very messy

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 }

Solution

  • Try assigning the html to a variable and return it in your 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;
    }