0
votes

I have two custom post types. One with the slug artwork and another with the slug research-materials. The permalink structure for an artwork post is http://example.com/artwork/artwork-slug and this is expected, works fine and what I want. On the post.php page for any post that is of the research-materials post type I have a custom field (via ACF) that has the slug of the artwork post that the research materials post is related to and the desired slug for the research materials post. There's also a custom taxonomy set for the research-materials post type which would play a part in the construction of the permalink structure for the research-materials posts. The permalink would look like http://example.com/artwork/related-artwork-slug/research-materials/custom-taxonomy-term/research-materials-slug

Here's the code I have so far but I'm not getting the result I'd expect... instead I'm redirected to the artwork custom post type when I should be redirected tot he research-materials custom post type single page.

Any help appreciated. Thanks in advance.

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

1 Answers

0
votes

After much tinkering I figured it out. There were a lot of small things wrong with the above code and I also had to make use of the index_template hook. Here's the final code:

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();