I have an html snippet saved as a php file (e.g. mywidget.php
):
<?php
if (!defined('ABSPATH')) exit;
?>
<div>
foo bar baz
</div>
In a separate file mywidget-block.php
, how can I create a block that "wraps" the markup from mywidget.php
?
The block documentation is quite involved, and I'm hoping to create this simplest of blocks, without having to learn react. All it does is output html saved in some php file.
I have an html snippet saved as a php file (e.g. mywidget.php
):
<?php
if (!defined('ABSPATH')) exit;
?>
<div>
foo bar baz
</div>
In a separate file mywidget-block.php
, how can I create a block that "wraps" the markup from mywidget.php
?
The block documentation is quite involved, and I'm hoping to create this simplest of blocks, without having to learn react. All it does is output html saved in some php file.
Share Improve this question asked Dec 30, 2019 at 8:11 lonixlonix 3011 silver badge10 bronze badges1 Answer
Reset to default 0If you are working on a Wordpress Theme you can use the function:
get_template_part( string $slug, string $name = null )
Wich loads a template part into a php template.
get_template_part() will do a PHP require() for the first file that exists...
So effectively it will work as if you were requiring another php file. For example, in your case, you can have in your mywidget-block.php
:
<?php
// some block that "wraps" the markup from mywidget.php
get_template_part('theme-templates/mywidget');
// more code wrapping the markup
?>
And in your mywidget.php
, all the code you had:
<?php
if (!defined('ABSPATH')) exit;
?>
<div>
foo bar baz
</div>
This example is assuming that you have your mywidget.php
inside a folder called theme-templates in your theme root. Here is the documentation of this function.
Remember that get_template_part()
is a theme function, therefore you can't load plugin files with that function. If you are developing a Wordpress plugin then I recommend this post to you, wich describes how to use a function that will do the work of loading your plugin templates, while allowing users to override your plugin templates within their theme. Basically, what it does is looks in a special folder in the theme, then if not found there, it looks within the templates folder for the plugin.