0

Trying to create a shortcode to be implemented to a popup. I'm trying to display four images in a 2x2 grid at the center of the page. The problem is that this shortcode now floats everything left and the images display vertically on top of each other instead of 2x2 at the center of the page.

Also, the contents displayed on the top of every page (before page content) when I implement the shortcode in the popup, it doesn't display in the popup though.

I've tried:

ob_start();
return ob_get_clean();

That stops it from displaying in the head of every page, but it doesn't output anything else either.

What am I doing wrong?

Adding my shortcode function here and the CSS for the 2x2 grid layout underneath.

Shortcode Function:

<?php
function my_function() {

$args = array (
    'post_type'              => 'my_cpt',
    'nopaging'               => false,
    'posts_per_page'         => '4',
    'order'                  => 'ASC',
    'orderby'                => 'rand',
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();

$image = get_field('my_image_field');
$size = 'medium';?>

<div class="grid2x2">
        <div class="thegridbox">
        <div>'  
                ?><a href="<?php the_field('my_image_link'); ?> ">
                    <img src="<?php wp_get_attachment_image( $image, $size ); ?>" />
                </a>                
        </div>  
    </div>
</div>

<?php

}

} else {

echo 'Oops! Nothing found.';

}

wp_reset_postdata();    

}
add_shortcode( 'my_shortcode', 'my_function' );
?>

CSS for the 2x2 frid layout:

.grid2x2 {
  min-height: 100%;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
}
.grid2x2 > div {
  display: flex; 
  flex-basis: calc(50% - 40px);  
  justify-content: center;
  flex-direction: column;
}
.grid2x2 > div > div {
  display: flex;
  justify-content: center;
  flex-direction: row;
}

.thegridbox { margin: 20px; }
  • Where are you putting ob_start() it needs to go before any output. The whole point is to capture the output and return it. – Jacob Peattie Dec 20 '18 at 12:18
  • I added ob_start() right below function my_function(){ and return ob_get_clean(); right before wp_reset_postdata();. – re-boot Dec 20 '18 at 12:28
0

As we can see on the Codex, all strings produced in a Shortcode must be returned instead of echoing them.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.