最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Block that renders html saved in a php file

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论