L
L
ligisayan2018-08-23 19:14:43
WordPress
ligisayan, 2018-08-23 19:14:43

How to sum rows in wordpress shortcode?

Hello! I want to write a shortcode that will display the last 5 taxonomy posts. The whole catch is that I don't know how to sum the lines at this point:

$cont += "<li><a href='". $post->guid. "'>" . $post->post_title . "</a></li><br />";

because for good, the attributes $postshould be output via echo and if I substitute in the expression above, I get an error.
The code:
function shortcode_function() {

  $args = array(
  'numberposts' => 5,
  'category'    => 0,
  'orderby'     => 'date',
  'order'       => 'DESC',
  'meta_key'    => '',
  'meta_value'  =>'',
  'post_type'   => 'movies',
  'suppress_filters' => true,
);

$posts = get_posts( $args );
$cont = 0;

foreach( $posts as $post ){ 
setup_postdata($post);

   $cont += "<li><a href='". $post->guid. "'>" . $post->post_title . "</a></li><br />";
}

  return $cont;

}
add_shortcode( 'show_films', 'shortcode_function' );

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
ligisayan, 2018-08-23
@ligisayan

My task is solved by buffering the output of ob_start() - ob_get_clean()

function shortcode_function() {
ob_start();
  $args = array(
  'numberposts' => 5,
  'category'    => 0,
  'orderby'     => 'date',
  'order'       => 'DESC',
  'meta_key'    => '',
  'meta_value'  =>'',
  'post_type'   => 'movies',
  'suppress_filters' => true,
);

$posts = get_posts( $args );
$cont = 0;

foreach( $posts as $post ){ 
setup_postdata($post); 
 ?>
<li><a href="<?php echo $post->guid; ?>"><?php echo $post->post_title; ?></a></li>

<?php }
$cont = ob_get_clean();
  return $cont;

}
add_shortcode( 'show_films', 'shortcode_function' );

W
Way, 2018-08-24
@wayheming

$cont += ''; in PHP strings need to be concatenated via . i.e. $cont .= '';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question