Forked from mihdan/passing-variables-to-get_template_part-in-wordpress.php
Created
October 22, 2019 18:46
-
-
Save artikus11/97597fc4699f034e277167d0385cfc32 to your computer and use it in GitHub Desktop.
Передача переменных для get_template_part()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Load a template part into a template | |
* | |
* @param string $slug The slug name for the generic template. | |
* @param string $name The name of the specialised template. | |
* @param array $params Any extra params to be passed to the template part. | |
*/ | |
function get_template_part_extended( $slug, $name = null, $params = array() ) { | |
if ( ! empty( $params ) ) { | |
foreach ( (array) $params as $key => $param ) { | |
set_query_var( $key, $param ); | |
} | |
} | |
get_template_part( $slug, $name ); | |
} | |
/** | |
* Получить шаблон, передав в него переменные | |
* | |
* @param string $slug слюг шаблона | |
* @param string|null $name имя шаблона | |
* @param array $params массив передаваемых переменных | |
* | |
* @return string | |
*/ | |
function teamrussia_get_template_parts( $slug, $name = null, $params = array() ) { | |
// Хукаем | |
do_action( 'get_template_part_' . $slug, $slug, $name ); | |
// Буферизуем | |
ob_start(); | |
// Формируем имя шаблона. | |
$templates = array(); | |
$name = (string) $name; | |
// Если кроме слюга передано имя, | |
// добавим его к названию шаблона. | |
if ( '' !== $name ) { | |
$templates[] = "{$slug}-{$name}.php"; | |
} | |
$templates[] = "{$slug}.php"; | |
// Извлекаем переменные, если они переданы. | |
if ( ! empty( $params ) ) { | |
extract( $params, EXTR_SKIP ); | |
} | |
// Подключить шаблоны | |
foreach ( $templates as $template ) { | |
include( locate_template( $template ) ); | |
} | |
// Вернем отрендеренный шаблон. | |
return ob_get_clean(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment