Получите содержимое шаблонов блоков Wordpress, подобное $post_content.Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Получите содержимое шаблонов блоков Wordpress, подобное $post_content.

Сообщение Anonymous »

Код: Выделить всё

get_block_templates()
получает все block_templates на сайте, но мне нужны только те, которые загружены для текущей страницы.
Я пытаюсь проверить, есть ли короткий код внутри одного из шаблонов редактора сайта Gutenberg. Он не сохраняется в $post_content или $template.
Это позволяет проверить каждый из них

Код: Выделить всё

    $templates = get_posts(array(
'post_type' => array('wp_template'),
'numberposts' => -1,
'fields' => 'ids'
));

foreach ($templates as $template_id) {
$template_content = get_post_field('post_content', $template_id);
if (has_shortcode($template_content, 'xxxx')) {
styles_and_scripts();
return;
}
}
Но я хочу только проверить, что загружается на страницу.
Я видел, что плагин монитора запросов выводит шаблон основного блока в шаблонах вкладок > шаблон блокаЭто код монитора запросов, который выводит правильный шаблон и, похоже, получает его идентификатор:

Код: Выделить всё

                echo '
';
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo self::build_link(
QM_Util::get_site_editor_url( $data->block_template->id, 'wp_template' ),
esc_html( $data->block_template->id )
);
echo '
';
}
Мне удалось отменить решение контроля качества для вывода содержимого шаблона, но это не идеально:

Код: Выделить всё

class Template_Debugger {
protected $template_path = '';
protected $block_template = null;

public function __construct() {
add_action('template_redirect', [$this, 'action_template_redirect']);
add_action('wp_footer', [$this, 'output_template_data']);
}

public function action_template_redirect() {
add_filter('template_include', [$this, 'filter_template_include'], PHP_INT_MAX);
$this->detect_block_template();
}

public function filter_template_include($template_path) {
$this->template_path = $template_path;

if ($this->block_template instanceof WP_Block_Template) {
$this->template_path = $this->block_template->theme . '/' . $this->block_template->slug;
}

return $template_path;
}

public function output_template_data() {
if ($this->template_path) {
$contents = $this->get_template_contents();
if ($contents) {
echo '
' . esc_html($contents) . '';
}
}
}

protected function detect_block_template() {
foreach ($this->get_query_template_names() as $template => $conditional) {
if ($this->block_template) {
break;
}
$get_template = "get_{$template}_template";
if (function_exists($conditional) && function_exists($get_template) && call_user_func($conditional)) {
$filter = str_replace('_', '', $template);
add_filter("{$filter}_template_hierarchy", [$this, 'filter_template_hierarchy'], PHP_INT_MAX);
add_filter("{$filter}_template", [$this, 'filter_template'], PHP_INT_MAX, 3);
call_user_func($get_template);
remove_filter("{$filter}_template_hierarchy", [$this, 'filter_template_hierarchy'], PHP_INT_MAX);
remove_filter("{$filter}_template", [$this, 'filter_template'], PHP_INT_MAX);
}
}
}

public function filter_template_hierarchy($templates) {
return $templates;
}

public function filter_template($template, $type, $templates) {
$block_template = $this->wp_resolve_block_template($type, $templates, $template);
if ($block_template) {
$this->block_template = $block_template;
$this->template_path = $block_template->theme . '/' .  $block_template->slug;
}
return $template;
}

protected function wp_resolve_block_template($template_type, $template_hierarchy, $fallback_template) {
if (!function_exists('resolve_block_template') || !current_theme_supports('block-templates')) {
return null;
}
return resolve_block_template($template_type, $template_hierarchy, $fallback_template);
}

protected function get_template_contents() {
if (!$this->template_path) {
return null;
}

if ($this->block_template instanceof WP_Block_Template) {
$template = get_block_template($this->block_template->id, 'wp_template');
return $template ? $template->content : null;
} else {
return file_exists($this->template_path) ? file_get_contents($this->template_path) : null;
}
}

protected function get_query_template_names() {
return [
'embed' => 'is_embed',
'404' => 'is_404',
'search' => 'is_search',
'front_page' => 'is_front_page',
'home' => 'is_home',
'privacy_policy' => 'is_privacy_policy',
'post_type_archive' => 'is_post_type_archive',
'taxonomy' => 'is_tax',
'attachment' => 'is_attachment',
'single' => 'is_single',
'page' => 'is_page',
'singular' => 'is_singular',
'category' => 'is_category',
'tag' => 'is_tag',
'author' => 'is_author',
'date' => 'is_date',
'archive' => 'is_archive',
'index' => '__return_true',
];
}
}

new Template_Debugger();

$post_content легко выводит все. Как я могу получить содержимое страницы, созданной сайтом Гутенберга, таким простым способом вместо того решения, которое у меня есть?

Код: Выделить всё

get_block_template()
подойдет отлично, но мне нужен простой способ получить идентификатор шаблона за пределами моего чудовищного решения.

Подробнее здесь: https://stackoverflow.com/questions/787 ... st-content
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»