/**
* Update the permalink structure.
*
* ## DESCRIPTION
*
* Updates the post permalink structure.
*
* To regenerate a .htaccess file with WP-CLI, you'll need to add the mod_rewrite module
* to your wp-cli.yml or config.yml. For example:
*
* `apache_modules:
* - mod_rewrite`
*
* ## OPTIONS
*
* <permastruct>
* : The new permalink structure to apply.
*
* [--category-base=<base>]
* : Set the base for category permalinks, i.e. '/category/'.
*
* [--tag-base=<base>]
* : Set the base for tag permalinks, i.e. '/tag/'.
*
* [--hard]
* : Perform a hard flush - update `.htaccess` rules as well as rewrite rules in database.
*
* ## EXAMPLES
*
* wp rewrite structure '/%year%/%monthnum%/%postname%'
*/
public function structure($args, $assoc_args)
{
global $wp_rewrite;
// copypasta from /wp-admin/options-permalink.php
$prefix = $blog_prefix = '';
if (is_multisite() && !is_subdomain_install() && is_main_site()) {
$blog_prefix = '/blog';
}
$permalink_structure = $args[0] == 'default' ? '' : $args[0];
if (!empty($permalink_structure)) {
$permalink_structure = preg_replace('#/+#', '/', '/' . str_replace('#', '', $permalink_structure));
if ($prefix && $blog_prefix) {
$permalink_structure = $prefix . preg_replace('#^/?index\\.php#', '', $permalink_structure);
} else {
$permalink_structure = $blog_prefix . $permalink_structure;
}
}
$wp_rewrite->set_permalink_structure($permalink_structure);
// Update category or tag bases
if (isset($assoc_args['category-base'])) {
$category_base = $assoc_args['category-base'];
if (!empty($category_base)) {
$category_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $category_base));
}
$wp_rewrite->set_category_base($category_base);
}
if (isset($assoc_args['tag-base'])) {
$tag_base = $assoc_args['tag-base'];
if (!empty($tag_base)) {
$tag_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $tag_base));
}
$wp_rewrite->set_tag_base($tag_base);
}
// make sure we detect mod_rewrite if configured in apache_modules in config
self::apache_modules();
// Launch a new process to flush rewrites because core expects flush
// to happen after rewrites are set
$new_assoc_args = array();
if (\WP_CLI\Utils\get_flag_value($assoc_args, 'hard')) {
$new_assoc_args['hard'] = true;
if (!in_array('mod_rewrite', (array) WP_CLI::get_config('apache_modules'))) {
WP_CLI::warning("Regenerating a .htaccess file requires special configuration. See usage docs.");
}
}
$process_run = WP_CLI::launch_self('rewrite flush', array(), $new_assoc_args, true, true, array('apache_modules', WP_CLI::get_config('apache_modules')));
if (!empty($process_run->stderr)) {
// Strip "Warning: "
WP_CLI::warning(substr($process_run->stderr, 9));
}
WP_CLI::success("Rewrite structure set.");
}