Подключение собственных компонентов в WordPress

Разрабатывая проект на WordPress я однажды столкнулся с потребностью подключать собсвенные расширения (некое подобие плагинов WordPress, но со своими плюшкми). WordPress использует некий header, для описания плагинов и тем. Выглядит он так:
/**
 * @package Hello_Dolly
 * @version 1.6
 */
/*
Plugin Name: Hello Dolly
Plugin URI: http://wordpress.org/extend/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.6
Author URI: http://ma.tt/
*/

Я решил сделать что-то подобное, вот мой заголовок:
/*
    Extension Name: 
    Extension URI:
    Version: 0.1
    Description: 
    Author:
    Author URI:
    Text Domain:
    Domain Path:
    Network:
    Site Wide Only:
*/

Для того чтоб распарсить это была написана функция:
function get_extension_data( $ext_file ) {

	$default_headers = array(
		'Name' => 'Extension Name',
		'ExtensionURI' => 'Extension URI',
		'Version' => 'Version',
		'Description' => 'Description',
		'Author' => 'Author',
		'AuthorURI' => 'Author URI',
		'TextDomain' => 'Text Domain',
		'DomainPath' => 'Domain Path',
		'Network' => 'Network',
		'_sitewide' => 'Site Wide Only',
		'DepsExts' => 'Dependence Extensions',
	);
	$ext_data = array();
	$ext_data = get_file_data( $ext_file, $default_headers );

	// Site Wide Only is the old header for Network
	if ( !$ext_data['Network'] && $ext_data['_sitewide'] ) {
		_deprecated_argument( __FUNCTION__, '3.0', sprintf( __( 'The <code>%1$s</code> plugin header is deprecated. Use <code>%2$s</code> instead.' ), 'Site Wide Only: true', 'Network: true' ) );
		$ext_data['Network'] = $ext_data['_sitewide'];
	}
	$ext_data['Network'] = ( 'true' == strtolower( $ext_data['Network'] ) );
	unset( $ext_data['_sitewide'] );
	
	$ext_data['Title'] = $ext_data['Name'];
	$ext_data['AuthorName'] = $ext_data['Author'];

	if ( $ext_data['DepsExts'] ) {
		$ext_data['DepsExts'] = explode( ',', $ext_data['DepsExts'] );
	}

	return $ext_data;

}

Она принимает путья к файлу расширения, в котором задан header и средствами WordPress парсит его, возвращая масив с данными. Парсингом занимается функция WordPress - get_file_data, которая принимает файл и элементы для поиска в header’e. Вот сама функции:
function get_file_data( $file, $default_headers, $context = '' ) {
	// We don't need to write to the file, so just open for reading.
	$fp = fopen( $file, 'r' );

	// Pull only the first 8kiB of the file in.
	$file_data = fread( $fp, 8192 );

	// PHP will close file handle, but we are good citizens.
	fclose( $fp );

	// Make sure we catch CR-only line endings.
	$file_data = str_replace( "\r", "\n", $file_data );

	if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
		$extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
		$all_headers = array_merge( $extra_headers, (array) $default_headers );
	} else {
		$all_headers = $default_headers;
	}

	foreach ( $all_headers as $field => $regex ) {
		if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
			$all_headers[ $field ] = _cleanup_header_comment( $match[1] );
		else
			$all_headers[ $field ] = '';
	}

	return $all_headers;
}

Полученые данные мне нужны для отображения информации о расширении в списке моих расширений (в моем варианте есть возможность активации/деактивации моих расширений). Потом я пробегаюсь по директории с расширениями и подключаю все активированые:
$extensions_dir = 'extensions_dir_path';
// Default method, only load activated extensions
foreach ( (array) $extensions['active'] as $ext ) {
	if ( file_exists( $extensions_dir.$ext ) && $ext != '' ) {
		include_once $extensions_dir.$ext;
	}
}

Теги:
extensions, wp header, парсинг заголовка файла, собсвенные расширения
Добавлено: 20 Мая 2018 20:53:10 Добавил: Андрей Ковальчук Нравится 0
Добавить
Комментарии:
Нету комментариев для вывода...