Skip to content

Instantly share code, notes, and snippets.

@andxbes
Last active June 30, 2023 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andxbes/97c4b07b6d5fad491e81fa2495212fc3 to your computer and use it in GitHub Desktop.
Save andxbes/97c4b07b6d5fad491e81fa2495212fc3 to your computer and use it in GitHub Desktop.
Кастомный url для таксономий
<?php
class Theme_Rewrite_Rules
{
public function __construct()
{
add_action('wp_loaded', [$this, '_maybe_rewrite_rules']);
add_action('init', [$this, '_change_term_struct']);
}
public static function is_live()
{
return ($_SERVER['HTTP_HOST'] == 'example.com');
}
public function _maybe_rewrite_rules()
{
// do not use on live/production servers
// На бете сбрасываем по изменению данного класса
// На лайве можно сбросить через отправку формы на странице /wp-admin/options-permalink.php
// или сменить тему
if (!self::is_live()) {
// Получим время файла, как номер версии
$ver = filemtime(__FILE__);
$defaults = array('version' => 0, 'time' => time());
$r = wp_parse_args(get_option(__CLASS__ . '_flush', array()), $defaults);
// Сбрасываем если изменилась версия .
if (
$r['version'] != $ver
) {
flush_rewrite_rules();
$args = array('version' => $ver, 'time' => time());
if (!update_option(__CLASS__ . '_flush', $args))
add_option(__CLASS__ . '_flush', $args);
}
}
}
public function _change_term_struct()
{
add_rewrite_rule('^projects/solution/([^/]+)/?', 'index.php?taxonomy=projects_solution&term=$matches[1]', 'top');
add_rewrite_rule('^projects/industry/([^/]+)/?', 'index.php?taxonomy=projects_industry&term=$matches[1]', 'top');
add_rewrite_rule('^projects/service/([^/]+)/?', 'index.php?taxonomy=projects_service&term=$matches[1]', 'top');
add_rewrite_rule('^projects/tech/([^/]+)/?', 'index.php?taxonomy=projects_tech&term=$matches[1]', 'top');
add_filter('query_vars', function ($vars) {
$vars[] = 'taxonomy';
$vars[] = 'term';
return $vars;
});
}
}
new Theme_Rewrite_Rules();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment