настраиваемая структура постоянных ссылок для настраиваемого типа записей на основе мета-полей и настраиваемой таксономии - PullRequest
0 голосов
/ 26 мая 2018

У меня есть два пользовательских типа сообщений.Один с слизней artwork, а другой с слизней research-materials.Структура постоянной ссылки для поста с художественными работами - http://example.com/artwork/artwork-slug, и это, как ожидается, работает нормально и то, что я хочу.На странице post.php для любого поста типа research-materials у меня есть настраиваемое поле (через ACF), в котором есть фрагмент поста с художественными работами, с которым связан пост исследовательских материалов, и требуемый фрагмент для исследования.материалы пост.Существует также специальный набор таксономии для типа поста исследовательских материалов, который будет играть роль в построении структуры постоянных ссылок для постов исследовательских материалов.Постоянная ссылка выглядела бы как http://example.com/artwork/related-artwork-slug/research-materials/custom-taxonomy-term/research-materials-slug

Вот код, который у меня есть, но я не получаю ожидаемого результата ... вместо этого я перенаправляюсь на пользовательский тип публикации, когда мне нужноБыть перенаправленным на исследовательские материалы. Пользовательский тип поста.

Любая помощь приветствуется.Заранее спасибо.

class RRP{
    public static function init(){
        // set up custom post types and custom taxonomies
        add_action( 'init', 'RRP::build_custom_post_types' );
        add_action( 'init', 'RRP::build_custom_taxonomy' );

        // set up custom fields
        add_action( 'acf/init', 'RRP::register_custom_fields' );

        // validate saved value in custom fields
        add_filter( 'acf/validate_value', 'RRP::validate_saved_value_in_custom_fields', 10, 4 );

        // update related artwork slug
        add_filter( 'acf/update_value', 'RRP::update_related_artwork_slug', 10, 3 );

        // add the research material type
        add_action( 'save_post_research-materials', 'RRP::set_research_material_type' );

        // build rewrite rules
        add_action( 'init', 'RRP::rewrite_stuff', 10, 0 );
        add_filter( 'query_vars', 'RRP::build_query_vars', 10 );
        add_filter( 'pre_get_posts', 'RRP::pre_get_posts', 10 );
    }
    public static function build_custom_post_types(){

        $labels = array(
            'name'                => 'Research Materials',
            'singular_name'       => 'Research Material',
            'add_new'             => 'Add New Research Material',
            'add_new_item'        => 'Add New Research Material',
            'edit_item'           => 'Edit Research Material',
            'new_item'            => 'New Research Material',
            'view_item'           => 'View Research Material',
            'search_items'        => 'Search Research Materials',
            'not_found'           => 'No Research Materials found',
            'not_found_in_trash'  => 'No Research Materials found in Trash',
            'parent_item_colon'   => 'Parent Research Material:',
            'menu_name'           => 'Research    Materials',
        );

        $args = array(
            'labels'              => $labels,
            'hierarchical'        => false,
            'description'         => 'description',
            'taxonomies'          => array('research-material-type'),
            'public'              => true,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'show_in_admin_bar'   => true,
            'menu_position'       => null,
            'menu_icon'           => null,
            'show_in_nav_menus'   => true,
            'publicly_queryable'  => true,
            'exclude_from_search' => false,
            'has_archive'         => true,
            'query_var'           => true,
            'can_export'          => true,
            'rewrite'             => true,
            'capability_type'     => 'post',
            'supports'            => array(
                'title', 'editor'
            )
        );

        register_post_type( 'research-materials', $args );

    }

    public static function build_custom_taxonomy(){

        $labels = array(
            'name'                  => 'Research Material Types',
            'singular_name'         => 'Research Material Type',
            'search_items'          => 'Search Research Material Types',
            'popular_items'         => 'Popular Research Material Types',
            'all_items'             => 'All Research Material Types',
            'parent_item'           => 'Parent Research Material Type',
            'parent_item_colon'     => 'Parent Research Material Type',
            'edit_item'             => 'Edit Research Material Type',
            'update_item'           => 'Update Research Material Type',
            'add_new_item'          => 'Add New Research Material Type',
            'new_item_name'         => 'New Research Material Type Name',
            'add_or_remove_items'   => 'Add or remove Research Material Types',
            'choose_from_most_used' => 'Choose from most used sfmomatheme',
            'menu_name'             => 'Research Material Type',
        );

        $args = array(
            'labels'            => $labels,
            'public'            => true,
            'show_in_nav_menus' => true,
            'show_admin_column' => false,
            'hierarchical'      => false,
            'show_tagcloud'     => true,
            'show_ui'           => true,
            'query_var'         => true,
            'rewrite'           => true,
            'query_var'         => true,
            'capabilities'      => array(),
        );

        register_taxonomy( 'research-material-type', array( 'research-materials' ), $args );

        $terms = get_terms('research-material-type');

        if( empty($terms) ){
            wp_insert_term( 'Document', 'research-material-type', array(
                'slug' => 'document',
            ) );
        }
    }

    public static function register_custom_fields(){
        acf_add_local_field_group(array(
            'key' => 'group_research_materials',
            'title' => 'Research Material Custom Fields',
            'fields' => array(
                array(
                    'key' => 'field_research_materials_slug',
                    'type' => 'text',
                    'name' => 'research_materials_slug',
                    'label' => 'Research Material Slug',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork',
                    'type' => 'relationship',
                    'name' => 'research_materials_related_artwork',
                    'label' => 'Related Artwork',
                    'post_type' => array(
                        'artwork',
                    ),
                    'max' => 1,
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork_slug',
                    'type' => 'text',
                    'name' => 'research_materials_related_artwork_slug',
                    'label' => 'Related Artwork Slug',
                    'disabled' => 1,
                    'instructions' => 'Generated based on Related Artwork',
                )
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'research-materials',
                    ),
                )
            ),
        ));
    }

    public static function validate_saved_value_in_custom_fields($valid, $value, $field, $input){
        if( empty($value) && $field['name'] !== 'research_materials_related_artwork_slug' ){
            $valid = 'Field must not be empty!';
        }
        return $valid;
    }

    public static function set_research_material_type($post_id){
        // build main term by default term or by whatever's the first result set
        $terms = wp_get_object_terms( strval($post_id), 'research-material-type' );
        $default_term = get_term_by( 'slug', 'document', 'research-material-type' );
        if( empty($terms) ){
            wp_set_object_terms( strval($post_id), $default_term->term_id, 'research-material-type' );
        }
        else{
            wp_set_object_terms( strval($post_id), $terms[0]->term_id, 'research-material-type' );
        }
    }

    public static function build_query_vars($vars){
        $vars[] = 'research_materials_related_artwork_slug';
        $vars[] = 'research_materials_slug';
        $vars[] = 'research_materials_type';
        return $vars;
    }

    public static function update_related_artwork_slug($value, $post_id, $field){
        if( $field['name'] === 'research_materials_related_artwork_slug' ){
            $value = get_field('research_materials_related_artwork', $post_id)[0]->post_name;
        }
        return $value;
    }

    public static function pre_get_posts($query){
        // check if the user is requesting an admin page 
        // or current query is not the main query
        if ( is_admin() || !$query->is_main_query() ){
            return;
        }

        $research_materials_related_artwork = get_query_var('research_materials_related_artwork_slug');

        $research_materials_slug = get_query_var('research_materials_slug');

        $research_materials_type = get_query_var('research_materials_type');

        if( !empty($research_materials_related_artwork) && !empty($research_material_slug) && !empty($research_materials_type) ){

            $meta_query = $query->get('meta_query');

            if( empty($meta_query) ){
                $meta_query = array(
                    'relation' => 'AND',
                    array(
                        'key' => 'research_materials_related_artwork_slug',
                        'value' => $research_materials_related_artwork,
                        'compare' => '==',
                    ),
                    array(
                        'key' => 'research_materials_slug',
                        'value' => $research_materials_slug,
                        'compare' => '==',  
                    )
                );
            }
            else{
                $meta_query[] = array(
                    'relation' => 'AND',
                    array(
                        'key' => 'research_materials_related_artwork_slug',
                        'value' => $research_materials_related_artwork,
                        'compare' => '==',
                    ),
                    array(
                        'key' => 'research_materials_slug',
                        'value' => $research_materials_slug,
                        'compare' => '==',  
                    )
                );
            }

            $query->set('meta_query', $meta_query);

            $tax_query = $query->get('tax_query');

            if( empty($tax_query) ){
                $tax_query = array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'research-material-type',
                        'field' => 'slug',
                        'terms' => array($research_materials_type),
                    )
                );
            }
            else{
                $tax_query[] = array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'research-material-type',
                        'field' => 'slug',
                        'terms' => array($research_materials_type),
                    )
                );
            }

            $query->set('tax_query', $tax_query);

        }

        return $query;
    }

    public static function rewrite_stuff(){
        add_rewrite_tag( '%research_materials_related_artwork_slug%', '([^&]+)' );
        add_rewrite_tag( '%research_materials_slug%', '([^&]+)' );
        add_rewrite_rule( '^artwork/([^/]*)/research-materials/([^/]*)/([^/]*)/?', 'index.php?post_type=research-materials&research_materials_related_artwork_slug=$matches[1]&research_materials_slug=$matches[2]&research_materials_type=$matches[3]', 'top' );
    }
}

RRP::init();

1 Ответ

0 голосов
/ 28 мая 2018

После долгих кований я понял это.В приведенном выше коде было много мелких ошибок, и мне также пришлось использовать хук index_template.Вот окончательный код:

class RRP{
    public static function init(){
        // set up custom post types and custom taxonomies
        add_action( 'init', 'RRP::build_custom_post_types' );
        add_action( 'init', 'RRP::build_custom_taxonomy' );

        // set up custom fields
        add_action( 'acf/init', 'RRP::register_custom_fields' );

        // validate saved value in custom fields
        add_filter( 'acf/validate_value', 'RRP::validate_saved_value_in_custom_fields', 10, 4 );

        // update related artwork slug
        add_filter( 'acf/update_value', 'RRP::update_related_artwork_slug', 10, 3 );

        // add the research material type
        add_action( 'save_post_research-materials', 'RRP::set_research_material_type' );

        // build rewrite rules
        add_filter( 'index_template', 'RRP::point_artwork_and_artist_to_single_templates' );
        add_action( 'init', 'RRP::rewrite_stuff', 0 );
        add_filter( 'query_vars', 'RRP::build_query_vars', 10 );
        add_filter( 'pre_get_posts', 'RRP::pre_get_posts', 10 );

    }
    public static function build_custom_post_types(){

        $labels = array(
            'name'                => 'Research Materials',
            'singular_name'       => 'Research Material',
            'add_new'             => 'Add New Research Material',
            'add_new_item'        => 'Add New Research Material',
            'edit_item'           => 'Edit Research Material',
            'new_item'            => 'New Research Material',
            'view_item'           => 'View Research Material',
            'search_items'        => 'Search Research Materials',
            'not_found'           => 'No Research Materials found',
            'not_found_in_trash'  => 'No Research Materials found in Trash',
            'parent_item_colon'   => 'Parent Research Material:',
            'menu_name'           => 'Research    Materials',
        );

        $args = array(
            'labels'              => $labels,
            'hierarchical'        => false,
            'description'         => 'description',
            'taxonomies'          => array('research-material-type'),
            'public'              => true,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'show_in_admin_bar'   => true,
            'menu_position'       => null,
            'menu_icon'           => null,
            'show_in_nav_menus'   => true,
            'publicly_queryable'  => true,
            'exclude_from_search' => false,
            'has_archive'         => true,
            'query_var'           => true,
            'can_export'          => true,
            'rewrite'             => array(
                'slug' => 'research-materials',
                'with_front' => false,
            ),
            'capability_type'     => 'post',
            'supports'            => array(
                'title', 'editor'
            )
        );

        register_post_type( 'research-materials', $args );

    }

    public static function build_custom_taxonomy(){

        $labels = array(
            'name'                  => 'Research Material Types',
            'singular_name'         => 'Research Material Type',
            'search_items'          => 'Search Research Material Types',
            'popular_items'         => 'Popular Research Material Types',
            'all_items'             => 'All Research Material Types',
            'parent_item'           => 'Parent Research Material Type',
            'parent_item_colon'     => 'Parent Research Material Type',
            'edit_item'             => 'Edit Research Material Type',
            'update_item'           => 'Update Research Material Type',
            'add_new_item'          => 'Add New Research Material Type',
            'new_item_name'         => 'New Research Material Type Name',
            'add_or_remove_items'   => 'Add or remove Research Material Types',
            'choose_from_most_used' => 'Choose from most used sfmomatheme',
            'menu_name'             => 'Research Material Type',
        );

        $args = array(
            'labels'            => $labels,
            'public'            => true,
            'show_in_nav_menus' => true,
            'show_admin_column' => false,
            'hierarchical'      => false,
            'show_tagcloud'     => true,
            'show_ui'           => true,
            'query_var'         => true,
            'rewrite'           => true,
            'query_var'         => true,
            'capabilities'      => array(),
        );

        register_taxonomy( 'research-material-type', array( 'research-materials' ), $args );

        $terms = get_terms('research-material-type');

        if( empty($terms) ){
            wp_insert_term( 'Document', 'research-material-type', array(
                'slug' => 'document',
            ) );
        }
    }

    public static function register_custom_fields(){
        acf_add_local_field_group(array(
            'key' => 'group_research_materials',
            'title' => 'Research Material Custom Fields',
            'fields' => array(
                array(
                    'key' => 'field_research_materials_slug',
                    'type' => 'text',
                    'name' => 'research_materials_slug',
                    'label' => 'Research Material Slug',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork',
                    'type' => 'relationship',
                    'name' => 'research_materials_related_artwork',
                    'label' => 'Related Artwork',
                    'post_type' => array(
                        'artwork',
                    ),
                    'max' => 1,
                    'required' => 1,
                ),
                array(
                    'key' => 'field_research_materials_related_artwork_slug',
                    'type' => 'text',
                    'name' => 'research_materials_related_artwork_slug',
                    'label' => 'Related Artwork Slug',
                    'disabled' => 1,
                    'instructions' => 'Generated based on Related Artwork',
                )
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'research-materials',
                    ),
                )
            ),
        ));
    }

    public static function validate_saved_value_in_custom_fields($valid, $value, $field, $input){
        if( empty($value) && $field['name'] !== 'research_materials_related_artwork_slug' ){
            $valid = 'Field must not be empty!';
        }
        return $valid;
    }

    public static function set_research_material_type($post_id){
        // build main term by default term or by whatever's the first result set
        $terms = wp_get_object_terms( strval($post_id), 'research-material-type' );
        $default_term = get_term_by( 'slug', 'document', 'research-material-type' );
        if( empty($terms) ){
            wp_set_object_terms( strval($post_id), $default_term->term_id, 'research-material-type' );
        }
        else{
            wp_set_object_terms( strval($post_id), $terms[0]->term_id, 'research-material-type' );
        }
    }

    public static function build_query_vars($vars){
        $vars[] = 'research_materials_related_artwork_slug';
        $vars[] = 'research_materials_slug';
        $vars[] = 'research_materials_type';
        return $vars;
    }

    public static function update_related_artwork_slug($value, $post_id, $field){
        if( $field['name'] === 'research_materials_related_artwork_slug' ){
            $value = get_field('research_materials_related_artwork', $post_id)[0]->post_name;
        }
        return $value;
    }

    public static function pre_get_posts($query){
        // check if the user is requesting an admin page 
        // or current query is not the main query
        if ( is_admin() || !$query->is_main_query() ){
            return;
        }

        $research_materials_related_artwork = $query->get('research_materials_related_artwork_slug');
        error_log(print_r($research_materials_related_artwork, true));
        $research_materials_slug = $query->get('research_materials_slug');
        error_log(print_r($research_materials_slug, true));
        $research_materials_type = $query->get('research_materials_type');
        error_log(print_r($research_materials_type, true));

        if( !empty($research_materials_related_artwork) && !empty($research_materials_slug) && !empty($research_materials_type) ){
            $meta_query = array(
                'relation' => 'AND',
                array(
                    'key' => 'research_materials_related_artwork_slug',
                    'value' => $research_materials_related_artwork,
                    'compare' => '=',
                ),
                array(
                    'key' => 'research_materials_slug',
                    'value' => $research_materials_slug,
                    'compare' => '=',   
                )
            );

            $query->set('meta_query', $meta_query);

            $tax_query = array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'research-material-type',
                    'field' => 'slug',
                    'terms' => array($research_materials_type),
                )
            );

            $query->set('tax_query', $tax_query);   
        }
        return $query;
    }
    // needed because I also have a CPT called artwork
    public static function point_artwork_and_artist_to_single_templates($templates = ''){
        global $post;
        if( $post->post_type == 'research-materials' ){
            $templates = locate_template( 'single-research-materials.php' );
        }
        return $templates;
    }
    public static function rewrite_stuff(){
        add_rewrite_tag( '%research_materials_related_artwork_slug%', '([^&]+)' );
        add_rewrite_tag( '%research_materials_slug%', '([^&]+)' );
        add_rewrite_tag( '%research_materials_type%', '([^&]+)' );
        add_rewrite_rule( 'artwork\/(.*)\/research-materials\/(.*)\/(.*)\/?$', 'index.php?post_type=research-materials&research_materials_related_artwork_slug=$matches[1]&research_materials_type=$matches[2]&research_materials_slug=$matches[3]', 'top' );
    }
}

RRP::init();
...