WP - Использовать файл в каталоге плагинов в качестве настраиваемого шаблона страницы?
Возможно ли, что файл в каталоге плагина используется в качестве настраиваемого шаблона страницы?
Также, как вы создаете плагин для создания страницы?
Я разрабатываю плагин для клиента на основе темы, он хочет, чтобы этот плагин создавал страницы продаж, имея возможность использовать свою тему на главной странице. Это продукт, который я делаю для него на рынок, поэтому его нужно автоматизировать через плагин.
Возможно ли это?
ИЗМЕНИТЬ
У меня есть крючки активации/деактивации в основном файле плагинов, и он не работает. Здесь код:
$filename = __FILE__;
register_activation_hook($filename, 'superActivation');
register_deactivation_hook($filename, 'superDeactivation');
global $myFile; global $fh; global $stringData; global $filename;
$myFile = "testFile.txt";
$stringData = "Testing\n";
$fh = fopen($myFile, 'w') or die("can't open file");
function superActivation() {
global $myFile; global $fh; global $stringData; global $filename;
fwrite($fh, $stringData);
fclose($fh);
}
function superDeactivation() {
$myFile = "testFile.txt";
unlink($myFile);
}
Ответы
Ответ 1
Вы можете сделать это с помощью шаблона hook. Здесь мой код, чтобы вручную заменить шаблон для персонализированного типа сообщения одним в теме, если в папке шаблона нет. Поместите это в свой файл плагина, а затем поместите папку под вашим плагином под названием themefiles с файлами темы по умолчанию.
//Template fallback
add_action("template_redirect", 'my_theme_redirect');
function my_theme_redirect() {
global $wp;
$plugindir = dirname( __FILE__ );
//A Specific Custom Post Type
if ($wp->query_vars["post_type"] == 'product') {
$templatefilename = 'single-product.php';
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect($return_template);
//A Custom Taxonomy Page
} elseif ($wp->query_vars["taxonomy"] == 'product_categories') {
$templatefilename = 'taxonomy-product_categories.php';
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect($return_template);
//A Simple Page
} elseif ($wp->query_vars["pagename"] == 'somepagename') {
$templatefilename = 'page-somepagename.php';
if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect($return_template);
}
}
function do_theme_redirect($url) {
global $post, $wp_query;
if (have_posts()) {
include($url);
die();
} else {
$wp_query->is_404 = true;
}
}
Ответ 2
Вы CAN легко добавляете шаблоны страниц из плагина, манипулируя кешем страницы.
Чтобы настроить, просто отредактируйте следующий код в методе __construct;
$this->templates = array(
'goodtobebad-template.php' => 'It\ Good to Be Bad',
);
Это предназначено для плагина (файлы шаблонов ищутся в корневом каталоге плагина). При необходимости это можно изменить - ознакомьтесь с моим полным учебником http://www.wpexplorer.com/wordpress-page-templates-plugin/ для получения более подробной информации об этом решении. Эти файлы также находятся в точно таком же формате, как если бы они были включены непосредственно в тему.
Полный код;
class PageTemplater {
/**
* A Unique Identifier
*/
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter(
'page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter(
'wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it path
add_filter(
'template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It\ Good to Be Bad',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}
else { echo $file; }
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
Ознакомьтесь с моим руководством по этому вопросу для получения дополнительной информации.
http://www.wpexplorer.com/wordpress-page-templates-plugin/
Надеюсь, это поможет вам в том, что вы хотите сделать:)
Ответ 3
приведенный выше код david почти работает для меня. но он, кажется, покрывает все сообщения и страницы для меня. Этот код ниже отлично подходит для добавления шаблона к одному типу сообщений, который создается моим основным файлом плагина
function get_book_post_type_template($single_template) {
global $post;
if ($post->post_type == 'books') {
$single_template = dirname( __FILE__ ) . '/themefiles/single-books.php';
}
return $single_template;
}
add_filter( "single_template", "get_book_post_type_template" ) ;
но у меня возникли проблемы с его работой с настраиваемыми шаблонами страниц, у которых нет post_type или есть страница post_type =, например, можно сказать, что пользовательская страница является страницей входа в вспомогательный элемент, чтобы видеть мои пользовательские сообщения. в моем случае этот файл называется myaccount.php, и я включил его в подпапку в моей плагиновой папке с именем themefiles.
//Add Page and Post Template Files to Current Theme
add_action("template_redirect", 'my_account_redirect');
function my_account_redirect() {
global $wp;
//Set myAccount Custom Page Template
if (isset($wp->query_vars['pagename'] ) == "myaccount") {
$templatefilename = 'myAccount.php';
if (file_exists(dirname( __FILE__ ) . '/themefiles/' . $templatefilename)) {
$return_template = dirname( __FILE__ ) . '/themefiles/' . $templatefilename;
}
do_account_redirect($return_template);
}
}
//Finishing setting templates
function do_account_redirect($url) {
global $post, $wp_query;
if (have_posts()) {
include($url);
die();
} else {
$wp_query->is_404 = true;
}
}
когда я делаю вышеуказанный код, шаблон myaccount отображается на всех страницах, кроме дома, который, я считаю, потому, что он настроен на blogroll вместо статической страницы
Ответ 4
Я не могу ответить на user1912899, но их рекомендация кажется самым элегантным решением. Чтобы использовать настраиваемый шаблон для переопределения single-post.php, я внедрил следующий код. Это будет работать для любого настраиваемого файла - ****. Php, который вы добавите в свой плагин. Если он не существует, он просто возвращается к тому, что обычно использует WordPress.
add_action('template_include', 'my_template_include');
function my_template_include($template) {
$file = dirname( __FILE__ ).'/theme/single-'.get_post_type().'.php';
if(file_exists($file)) {
$template = $file;
}
return $template;
}