Wordpress shortcode to insert layouts

Asked

Viewed 45 times

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 on 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 place the files with the layouts in the folder '/layouts', inside the folder of the template, and when calling the shortcode, displays the contents of the file.

This was the solution that I found, because no type of code with includes worked, however it is taking too long to load, include common?

1 answer

1


Use get_template_part() to give the include using the Wordpress API. It is simpler, fails silently (no error if the file does not exist) and still allows access to templates 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']

?>
  • Thank you very much, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.