SanSolo
SanSolo

Reputation: 2373

How to ensure shortcode result doesn't break formatting?

I want to add a shortcode which will execute a DB query and return the result. Here's my functions.php:

function get_posts_count($cat){
    global $wpdb;  
    $a = shortcode_atts( array(
      'id' => ''
   ), $cat );
  $id=$a['id'];
  $count=$wpdb->get_results( "SELECT `count` FROM `wpmy_term_taxonomy` WHERE `term_id`=$id");
foreach($count as $row)
echo '('.$row->count.')';
  }

add_shortcode( 'postCount', 'get_posts_count' ); 

This is the shortcode in the editor:

enter image description here And here's the end result:

enter image description here

The value in this case 1 appears above the text Real Estate. How can I make sure it is displayed within the line? Thanks in advance

Upvotes: 0

Views: 27

Answers (1)

devthebuilder
devthebuilder

Reputation: 101

the shortcode accepts parameters (attributes) and return a result (the shortcode output). If the shortcode produces a HTML then ob_start can be used to capture output and convert it to a string as follows:-

function get_posts_count( $cat ) {
  ob_start();
  global $wpdb;

  $a     = shortcode_atts( array(
    'id' => '',
  ), $cat );
  $id    = $a['id'];

  $count = $wpdb->get_results( "SELECT `count` FROM `wpmy_term_taxonomy` WHERE `term_id`=$id" );

  foreach ( $count as $row ) {
    echo '(' . $row->count . ')';
  }

  return ob_get_clean();

}

add_shortcode( 'postCount', 'get_posts_count' );  

Upvotes: 1

Related Questions