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:

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:

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() ) {

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

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



} else {

echo 'Oops! Nothing found.';



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. Dec 20, 2018 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, 2018 at 12:28

1 Answer 1


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 agree to our terms of service and acknowledge you have read our privacy policy.

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