Описание
Обновляет правила перезаписи ссылок (ЧПУ) в БД и кэше.
Нужно использовать после добавления новых правил перезаписи УРЛов, чтобы новые правила вступили в силу, иначе новые правила перезаписи работать не будут. Новые правила добавляются функцией .
add_rewrite_rule().
Эту функцию не нужно использовать постоянно! flush_rules() достаточно требовательна к ресурсам, поэтому, её нужно использовать одноразово, например, во время активации/деактивации плагина/темы. Нужно избегать использование функции постоянно при загрузке страницы, т.е. её не нужно вешать на хук, который постоянно вызывается при загрузке страницы, типа: init.
ВАЖНО: С версии 3.0. для обновления правил перезаписи существует функция flush_rewrite_rules().
Функция ничего не возвращает (void).
Использование
$wp_rewrite->flush_rules();
Шаблон использования
<?php global $wp_rewrite; $wp_rewrite->flush_rules(); ?>
Примеры
1. Пример обновления правил перезаписи УРЛов:
// Убедимся, что переменная $wp_rewrite определена глобально global $wp_rewrite; $wp_rewrite->flush_rules();
2. Пример обновления правил перезаписи с использованием функции flush_rewrite_rules(), во время активации плагина:
register_activation_hook( __FILE__, 'author_base_rewrite' );
function author_base_rewrite(){
flush_rewrite_rules( false );
}
flush_rewrite_rules( false ) - false указывает, что не нужно обновлять файл .htaccess, если не указать false, то файл .htaccess будет обновлен в соответствии с правилами.
На заметку
WordPress сохраняет все правила перезаписи в кэше. Иногда плагины, темы или функции могут добавить свои, новые правила перезаписи и WordPress ничего не будет знать об этих новых правилах, до тех пор, пока все правила не будут перезаписаны (обновлены).
Это не обычная функция, а метод класса WP_Rewrite, поэтому при вызове этого метода, нужно убедится что переменная $wp_rewrite, содержащая в себе экземпляр класса WP_Rewrite, определена глобально. Вызывать метод нужно по правилам классов: $wp_rewrite->flush_rules();.
ВАЖНО: Этот метод (функция) вызывается во время обновления настроек ЧПУ, поэтому для частного обновления правил перезаписи можно зайти на страницу настроек ЧПУ (параметры > постоянные ссылки) и, ничего не меняя, сохранить настройки.
flush_rules()
из файла: /wp-includes/rewrite.php WP 3.3.2function flush_rules($hard = true) {
delete_option('rewrite_rules');
$this->wp_rewrite_rules();
if ( $hard && function_exists('save_mod_rewrite_rules') )
save_mod_rewrite_rules();
if ( $hard && function_exists('iis7_save_url_rewrite_rules') )
iis7_save_url_rewrite_rules();
}
/**
* Sets up the object's properties.
*
* The 'use_verbose_page_rules' object property will be set to true if the
* permalink structure begins with one of the following: '%postname%', '%category%',
* '%tag%', or '%author%'.
*
* @since 1.5.0
* @access public
*/
function init() {
$this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
$this->permalink_structure = get_option('permalink_structure');
$this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));
$this->root = '';
if ( $this->using_index_permalinks() )
$this->root = $this->index . '/';
unset($this->author_structure);
unset($this->date_structure);
unset($this->page_structure);
unset($this->search_structure);
unset($this->feed_structure);
unset($this->comment_feed_structure);
$this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );
// Enable generic rules for pages if permalink structure doesn't begin with a wildcard.
if ( preg_match("/^[^%]*%(?:postname|category|tag|author)%/", $this->permalink_structure) )
$this->use_verbose_page_rules = true;
else
$this->use_verbose_page_rules = false;
}
/**
* Set the main permalink structure for the blog.
*
* Will update the 'permalink_structure' option, if there is a difference
* between the current permalink structure and the parameter value. Calls
* {@link WP_Rewrite::init()} after the option is updated.
*
* Fires the 'permalink_structure_changed' action once the init call has
* processed passing the old and new values
*
* @since 1.5.0
* @access public
*
* @param string $permalink_structure Permalink structure.
*/
function set_permalink_structure($permalink_structure) {
if ( $permalink_structure != $this->permalink_structure ) {
update_option('permalink_structure', $permalink_structure);
$this->init();
do_action('permalink_structure_changed', $this->permalink_structure, $permalink_structure);
}
}
/**
* Set the category base for the category permalink.
*
* Will update the 'category_base' option, if there is a difference between
* the current category base and the parameter value. Calls
* {@link WP_Rewrite::init()} after the option is updated.
*
* @since 1.5.0
* @access public
*
* @param string $category_base Category permalink structure base.
*/
function set_category_base($category_base) {
if ( $category_base != get_option('category_base') ) {
update_option('category_base', $category_base);
$this->init();
}
}
/**
* Set the tag base for the tag permalink.
*
* Will update the 'tag_base' option, if there is a difference between the
* current tag base and the parameter value. Calls
* {@link WP_Rewrite::init()} after the option is updated.
*
* @since 2.3.0
* @access public
*
* @param string $tag_base Tag permalink structure base.
*/
function set_tag_base( $tag_base ) {
if ( $tag_base != get_option( 'tag_base') ) {
update_option( 'tag_base', $tag_base );
$this->init();
}
}
/**
* Constructor - Calls init(), which runs setup.
*
* @since 1.5.0
* @access public
*
* @return WP_Rewrite
*/
function __construct() {
$this->init();
}
}Связанные Функции
Ещё из раздела
Смотрите также: Функции WordPress и Теги Шаблона.
Технология печати сегодня современна как никогда и печатать можно практически на всем: бумага, текстильные изделия, керамическая посуда и т.д. Одним из видов принтеров являются термотрансферные, которые используют риббон для печати. Риббон - это лента (полиэтиленовая пленка) с одной стороны которой находится краска, а с другой антистатическое покрытие, защищающее головку принтера. Риббон — основной расходный материал принтера.