Block that renders html saved in a php file

I have an html snippet saved as a php file (e.g. mywidget.php):<?phpif (!defined('ABSPATH')) exit;?>&l

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

If 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744870374a4598225.html

相关推荐

  • Block that renders html saved in a php file

    I have an html snippet saved as a php file (e.g. mywidget.php):<?phpif (!defined('ABSPATH')) exit;?>&l

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信