Shortcode Wordpress to insert layouts

1

I am creating a Wordpress template for a client, and I need to insert layouts in the pages, so I created the following shortcode in the functions.php of the template:

<?php

function shortcode_add_layout( $atts , $content = null ) {
   extract(
      shortcode_atts(
         array(
            'add' => 'home',
         ),
         $atts
      )
   );

   $file = get_template_directory_uri() . '/layouts/' . $add . '.php';

   if (!file_exists($file)) {
      echo file_get_contents($file);
   } else {
      echo 'Oops, layout not found';
   }
}

add_shortcode('layout', 'shortcode_add_layout');

# [layout add='home']

?>

With this, I put the files with the layouts in the '/ layouts' folder, inside the template folder, and when calling the shortcode, it displays the contents of the file.

This was the solution I found, since no code with includes worked, but it's taking too long to load, what can I do to make it faster, such as a% common%?

    
asked by anonymous 08.12.2017 / 05:47

1 answer

1

Use get_template_part() to give the include using the WordPress API. It is simpler, it fails silently (it does not give an error if the file does not exist) and it also allows access to the template manipulation filters:

<?php

function shortcode_add_layout( $atts , $content = null ) {
   extract(
      shortcode_atts(
         array(
            'add' => 'home',
         ),
         $atts
      )
   );

   get_template_part( 'layouts/' . $add );
}

add_shortcode('layout', 'shortcode_add_layout');

# [layout add='home']

?>
    
09.12.2017 / 01:25