Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
wiki post type and taxonomy registration, gives permalink structure http://site.ru/wiki/category/subcategory/post
<?php
// don't load directly
if (!defined('ABSPATH')) die('-1');
class CreditznatokAddwiki
{
private static $_instance;
static function getInstance()
{
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
function __construct()
{
add_action('init', array($this, 'register_taxes'));
add_action('init', array($this, 'register_wiki'));
add_filter('post_type_link', array($this, 'wiki_permalink'), 1, 2);
add_filter( 'request', array($this, 'resolve_post_term' ));
}
function register_wiki()
{
/**
* Post Type: Термины.
*/
//add_rewrite_tag('%category_for_wiki%', '([^&/]+)');
$labels = array(
"name" => __("Термины", ""),
"singular_name" => __("Термины", ""),
"menu_name" => __("Термины", ""),
"all_items" => __("Все Термины", ""),
"add_new" => __("Добавить", ""),
"add_new_item" => __("Добавить термин", ""),
"edit_item" => __("Редактировать", ""),
"new_item" => __("Добавить", ""),
"view_item" => __("Просмотр", ""),
"search_items" => __("Поиск Термина", ""),
"not_found" => __("Термины не найдены", ""),
"not_found_in_trash" => __("Статей в корзине не найдена", ""),
"featured_image" => __("Миниатюра Термина", ""),
"set_featured_image" => __("Установить миниатюру", ""),
"remove_featured_image" => __("Удалить миниатюру", ""),
"use_featured_image" => __("Использовать миниатюру", ""),
"archives" => __("Список акций", ""),
"attributes" => __("Атрибуты", ""),
);
$args = array(
"label" => __("Термины", ""),
"labels" => $labels,
"description" => "",
"public" => true,
"has_archive" => "wiki",
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => [
'slug' => 'wiki/%category_for_wiki%',
'with_front' => false,
'hierarchical' => false,
],
"query_var" => true,
"supports" => ["title", "editor", "thumbnail"],
"taxonomies" => ["category_for_wiki"],
);
register_post_type("wiki", $args);
}
function wiki_permalink($permalink, $post)
{
// выходим если это не наш тип записи: без холдера
if (strpos($permalink, '%category_for_wiki%') === FALSE)
return $permalink;
// Получаем элементы таксы
$terms = get_the_terms($post, 'category_for_wiki');
// если есть элемент заменим холдер
if ( !is_wp_error($terms) && !empty($terms) && is_object($terms[0]) )
if ($terms[0]->parent) {
$taxonomy_slug = get_taxonomy_parents($terms[0]->term_id, 'category_for_wiki', '/', true);
} else {
$taxonomy_slug = $terms[0]->slug;
}
// элемента нет, а должен быть...
else
$taxonomy_slug = 'no-cats';
return str_replace('%category_for_wiki%', $taxonomy_slug, $permalink);
}
function register_taxes()
{
/**
* Taxonomy: Рубрики.
*/
$labels = array(
"name" => __("Рубрики", ""),
"singular_name" => __("Рубрики Терминов", ""),
);
$args = array(
"label" => __("Рубрики", ""),
"labels" => $labels,
"public" => true,
"hierarchical" => true,
"show_ui" => true,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"query_var" => true,
"rewrite" => [
'slug' => 'wiki',
'with_front' => false,
'hierarchical' => true
],
"show_admin_column" => false,
"show_in_rest" => false,
"rest_base" => "",
"show_in_quick_edit" => true,
);
register_taxonomy("category_for_wiki", array("wiki"), $args);
}
/**
* Заменяет основной запрос на получение термина получением записи, если с таким slug имеется.
* Темин таксономии "category_for_wiki", запись (post_type=wiki).
*
* @param $query_vars
*
* @return array
*/
function resolve_post_term( $query_vars ) {
if ( is_admin() || empty( $query_vars['category_for_wiki'] ) ) {
return $query_vars;
}
$slug = explode( '/', $query_vars['category_for_wiki'] );
$post = get_page_by_path( end( $slug ), OBJECT, 'wiki' );
if ( $post ) {
$query_vars = [
'name' => $post->post_name,
'post_type' => 'wiki',
];
}
return $query_vars;
}
}
CreditznatokAddwiki::getInstance();
function get_taxonomy_parents($id, $taxonomy, $separator = '/', $nicename = false, $visited = array())
{
$chain = [];
$parent = get_term($id, $taxonomy);
if (is_wp_error($parent)) {
return $parent;
}
if ($nicename)
$name = $parent->slug;
else
$name = $parent->name;
if ( $parent->parent && ($parent->parent != $parent->term_id) && !in_array($parent->parent, $visited) ) {
$visited[] = $parent->parent;
$chain[] = get_taxonomy_parents($parent->parent, $taxonomy, '/', $nicename, $visited);
}
$chain[] = $name;
return implode( $separator, $chain );
}
@campusboy87

This comment has been minimized.

Copy link

campusboy87 commented Sep 7, 2018

class CreditznatokAddwiki {
    private static $_instance;

    static function getInstance() {
        if ( ! ( self::$_instance instanceof self ) ) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    function __construct() {
        add_action( 'init', [ $this, 'register_taxes' ] );
        add_action( 'init', [ $this, 'register_wiki' ] );
        add_filter( 'post_type_link', [ $this, 'wiki_permalink' ], 1, 2 );

    }

    function register_wiki() {
        /**
         * Post Type: Термины.
         */

        $labels = [
            "name"                  => __( "Термины", "" ),
            "singular_name"         => __( "Термины", "" ),
            "menu_name"             => __( "Термины", "" ),
            "all_items"             => __( "Все Термины", "" ),
            "add_new"               => __( "Добавить", "" ),
            "add_new_item"          => __( "Добавить термин", "" ),
            "edit_item"             => __( "Редактировать", "" ),
            "new_item"              => __( "Добавить", "" ),
            "view_item"             => __( "Просмотр", "" ),
            "search_items"          => __( "Поиск Термина", "" ),
            "not_found"             => __( "Термины не найдены", "" ),
            "not_found_in_trash"    => __( "Статей в корзине не найдена", "" ),
            "featured_image"        => __( "Миниатюра Термина", "" ),
            "set_featured_image"    => __( "Установить миниатюру", "" ),
            "remove_featured_image" => __( "Удалить миниатюру", "" ),
            "use_featured_image"    => __( "Использовать миниатюру", "" ),
            "archives"              => __( "Список акций", "" ),
            "attributes"            => __( "Атрибуты", "" ),
        ];

        $args = [
            "label"               => __( "Термины", "" ),
            "labels"              => $labels,
            "description"         => "",
            "public"              => true,
            "has_archive"         => "wiki",
            "show_in_menu"        => true,
            "exclude_from_search" => false,
            "capability_type"     => "post",
            "map_meta_cap"        => true,
            "hierarchical"        => false,
            "rewrite"             => [
                'slug'         => 'wiki/%category_for_wiki%',
                'with_front'   => false,
                'hierarchical' => false,
            ],
            "query_var"           => true,
            "supports"            => [ "title", "editor", "thumbnail" ],
            "taxonomies"          => [ "category_for_wiki" ],
        ];

        register_post_type( "wiki", $args );
    }

    function wiki_permalink( $permalink, $post ) {
        // выходим если это не наш тип записи: без холдера
        if ( strpos( $permalink, '%category_for_wiki%' ) === false ) {
            return $permalink;
        }

        // Получаем элементы таксы
        $terms = get_the_terms( $post, 'category_for_wiki' );
        // если есть элемент заменим холдер
        if ( ! is_wp_error( $terms ) && ! empty( $terms ) && is_object( $terms[0] ) ) {
            if ( $terms[0]->parent ) {
                $taxonomy_slug = get_taxonomy_parents( $terms[0]->term_id, 'category_for_wiki', '/', true );
            } else {
                $taxonomy_slug = $terms[0]->slug;
            }
        } // элемента нет, а должен быть...
        else {
            $taxonomy_slug = 'no-cats';
        }

        return str_replace( '%category_for_wiki%', $taxonomy_slug, $permalink );
    }

    function register_taxes() {
        /**
         * Taxonomy: Рубрики.
         */

        $labels = [
            "name"          => __( "Рубрики", "" ),
            "singular_name" => __( "Рубрики Терминов", "" ),
        ];

        $args = [
            "label"              => __( "Рубрики", "" ),
            "labels"             => $labels,
            "public"             => true,
            "hierarchical"       => true,
            "show_ui"            => true,
            "show_in_menu"       => true,
            "show_in_nav_menus"  => true,
            "query_var"          => true,
            "rewrite"            => [ 'slug' => 'wiki', 'with_front' => false, 'hierarchical' => true ],
            "show_admin_column"  => false,
            "show_in_rest"       => false,
            "rest_base"          => "",
            "show_in_quick_edit" => true,
        ];
        register_taxonomy( "category_for_wiki", [ "wiki" ], $args );
    }


}

CreditznatokAddwiki::getInstance();

/**
 * @param        $id
 * @param        $taxonomy
 * @param string $separator
 * @param bool   $nicename
 * @param array  $visited
 *
 * @return array|null|string|WP_Error|WP_Term
 */
function get_taxonomy_parents( $id, $taxonomy, $separator = '/', $nicename = false, $visited = [] ) {
    $chain  = [];
    $parent = get_term( $id, $taxonomy );

    if ( is_wp_error( $parent ) ) {
        return $parent;
    }

    if ( $nicename ) {
        $name = $parent->slug;
    } else {
        $name = $parent->name;
    }

    if ( $parent->parent && ( $parent->parent != $parent->term_id ) && ! in_array( $parent->parent, $visited ) ) {
        $visited[] = $parent->parent;
        $chain[]   = get_taxonomy_parents( $parent->parent, $taxonomy, '/', $nicename, $visited );

    }

    $chain[] = $name;

    return implode( $separator, $chain );
}

/**
 * Заменяет основной запрос на получение термина получением записи, если с таким slug имеется.
 * Темин таксономии "category_for_wiki", запись (post_type=wiki).
 *
 * @param $query_vars
 *
 * @return array
 */
function resolve_post_term( $query_vars ) {
    if ( empty( $query_vars['category_for_wiki'] ) ) {
        return $query_vars;
    }

    $slug = explode( '/', $query_vars['category_for_wiki'] );
    $post = get_page_by_path( end( $slug ), OBJECT, 'wiki' );

    if ( $post ) {
        $query_vars = [
            'name'      => $post->post_name,
            'post_type' => 'wiki',
        ];
    }

    return $query_vars;
}

add_filter( 'request', 'resolve_post_term' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.