Soporte » WordPress Avanzado » Varios Post Type con la misma taxonomia

  • Resuelto inigonz

    (@inigonz)


    Buenos días,

    Tengo una duda respecto a como obtener el post type de la taxonomía que estoy viendo, me explico:
    Tengo una taxonomía ‘departamentos’ enlazada a dos post type, ‘proyecto’ y ‘noticia’ y he creado el archivo de la taxonomía, ‘taxonomy-departarmentos.php’.

    En el menú he puesto los links de la taxonomia con el post type proyecto «$url = get_bloginfo( ‘url’ ) . ‘/proyecto/’ . $term->slug . ‘/’;» cuando pincho en el menú, me lleva a la pagina de la taxonomía, pero aunque en la url me pone que estoy en proyectos, me dice que el post type es noticia (ya que es el último de la lista).

    Como puedo obtener el current post type o cual es la mejor forma de hacer esto? ahora mismo, lo obtengo haciendo una búsqueda en la url, si me pone noticia o proyecto, pero no se si es un poco chapuza.

    Muchas gracias, saludos.

    • Este debate fue modificado hace 6 años, 5 meses por José Arcos.
Viendo 9 respuestas - de la 1 a la 9 (de un total de 9)
  • Moderador José Arcos

    (@josearcos)

    Hola @inigonz, tal como lo haces creo que está bien. También puedes usar la función get_post_type(). La verdad es que nunca he creado una Custom Taxonomy para dos Custom Post Types distintos, pero creo que no es nada descabellado. Cualquier duda, en el proceso compártela por aquí y lo intentamos juntos.

    Saludos.

    Iniciador del debate inigonz

    (@inigonz)

    Gracias por tu respuesta Jose.
    He probado con get_post_type() pero siempre me devuelve noticia, aunque esté visualizando un term con url de proyectos. El problema está que al tener dos post type la taxonomía, no sabe a cual tiene que pertenecer y no utiliza la url para saberlo.
    En el single de proyecto y noticia, me reconoce el post type sin problemas.

    Saludos

    buenas,
    En principio asignar una taxonomía a dos post type está permitido..así que el problema que te encuentras está mas bien derivado del uso que le quieres dar

    creo que es necesario que nos muestres código , cómo asignas la taxonomía a los dos cpt, dónde quieres mostrar la salida en taxonomy-departarmentos.php ? cómo obtienes el post type o listado..

    creo que la forma que construyes la url de menú.. no es correcta del todo, pero no estoy seguro. Como inyectas
    $url = get_bloginfo( ‘url’ ) . ‘/proyecto/’ . $term->slug . ‘/’;

    has considerado los rewrite? https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post

    Un saludo

    Iniciador del debate inigonz

    (@inigonz)

    Buenas Oldlastman, gracias por tu respuesta.

    Aquí te pongo el código, pero utilizo los rewrites como podrás ver a continuación:

    Creación de post type y la taxonomía, ademas de varias funciones como vista de columnas, filtro de categorías, …:

    <?php
    	if ( !class_exists( 'PostType' ) ) {
    
            class PostType {
    
                function __construct() {
                    // Adds the proyecto post type and taxonomies
                    	add_action( 'init', array( &$this, 'PostType_init' ), 0 );
    
                    // Adds columns in the admin view for thumbnail and taxonomies
                    	$postTypes = array( 'proyecto', 'noticia' );
                    	foreach ( $postTypes as $postType ) {
                    		add_filter( 'manage_edit-' . $postType . '_columns', array( &$this, 'PostType_edit_columns' ) );                	
                    	}
                    	add_action( 'manage_posts_custom_column', array( &$this, 'PostType_column_display' ), 10, 2 );
    
                    // Allows filtering of posts by taxonomy in the admin view
                    	add_action( 'restrict_manage_posts', array( &$this, 'add_taxonomy_filters' ) );
                }
    
                function PostType_init() {
                	$postTypes = array( 'proyecto', 'noticia' );
    
                	foreach ( $postTypes as $postType ) {
            			switch ($postType) {
            				case 'proyecto':
            					$icono = 'dashicons-screenoptions';
            					break;
            				
            				case 'noticia':
            					$icono = 'dashicons-info';
            					break;
            			}
    
            			// Register Post Types
    		                $labels = array(
    		                    'name'               => __( $postType . 's' ),
    		                    'singular_name'      => __( $postType ),
    		                    'add_new'            => __( 'Añadir nuevo' ),
    		                    'add_new_item'       => __( 'Añadir nuevo ' . $postType ),
    		                    'edit_item'          => __( 'Editar ' . $postType ),
    		                    'new_item'           => __( 'Nuevo ' . $postType ),
    		                    'view_item'          => __( 'Ver ' . $postType ),
    		                    'search_items'       => __( 'Buscar ' . $postType ),
    		                    'not_found'          => __( 'No se encontraron ' . $postType . 's' ),
    		                    'not_found_in_trash' => __( 'No se encontraron ' . $postType . 's en la papelera' )
    		                );
    
    		                $args = array(
    		                    'labels'             => $labels,
    		                    'public'             => true,
    		                    'publicly_queryable' => true,
    		                    'show_ui'            => true,
    		                    'show_in_menu'       => true,
    		                    'show_in_nav_menus'  => true,
    		                    'menu_position '     => 20,
    		                    'supports'           => array( 'title', 'editor', 'thumbnail', 'page-attributes', 'post-formats', 'revisions' ),
    		                    'capability_type'    => $postType,
    		                    'capabilities'       => array(
    		                        'edit_post'           => 'edit_' . $postType,
    		                        'read_post'           => 'read_' . $postType,
    		                        'delete_post'         => 'delete_' . $postType,
    		                        'edit_posts'          => 'edit_' . $postType . 's',
    		                        'edit_others_posts'   => 'edit_others_' . $postType . 's',
    		                        'publish_posts'       => 'publish_' . $postType . 's',
    		                        'read_private_posts'  => 'read_private_' . $postType . 's',
    		                        'create_posts'        => 'edit_' . $postType . 's',
    		                        'delete_posts'        => 'delete_' . $postType . 's',
    		                        'delete_others_posts' => 'delete_others_' . $postType . 's',
    		                    ),
    		                    'hierarchical'       => false,
    		                    'has_archive'        => $postType,
    		                    'rewrite'            => array(
    		                        'slug'           => $postType . '-item',
    		                        'hierarchical'   => true,
    		                        'with_front'     => false
    		                    ),
    		                    'menu_icon'          => $icono
    		                );
    
    		                $args = apply_filters( $postType . '_args', $args );		                
    		                register_post_type( $postType, $args );
                    }
    
                    // Registrar las taxonomias
    	                $taxonomy_departamento_labels = array(
    	                    'name'                       => __( 'Departamentos'),
    	                    'singular_name'              => __( 'Departamento'),
    	                    'search_items'               => __( 'Buscar Departamentos'),
    	                    'popular_items'              => __( 'Departamentos Populares'),
    	                    'all_items'                  => __( 'Todas los Departamentos'),
    	                    'parent_item'                => __( 'Padre del Departamento'),
    	                    'parent_item_colon'          => __( 'Padre del Departamento:'),
    	                    'edit_item'                  => __( 'Editar el Departamento' ),
    	                    'update_item'                => __( 'Actualizar el Departamento' ),
    	                    'add_new_item'               => __( 'Añadir nuevo Departamento' ),
    	                    'new_item_name'              => __( 'Nuevo Departamento' ),
    	                    'separate_items_with_commas' => __( 'Separar los Departamentos por comas' ),
    	                    'add_or_remove_items'        => __( 'Añadir o Borrar Departamentos' ),
    	                    'choose_from_most_used'      => __( 'Elegir entre los Departamentos mas usados' ),
    	                    'menu_name'                  => __( 'Departamentos' ),
    	                );
    
    	                $taxonomy_departamento_args = array(
    	                    'labels'            => $taxonomy_departamento_labels,
    	                    'public'            => true,
    	                    'capabilities'      => array(
    	                        'manage_terms'  => 'manage_departamentos',
    	                        'edit_terms'    => 'edit_departamentos',
    	                        'delete_terms'  => 'delete_departamentos',
    	                        'assign_terms'  => 'assign_departamentos',
    	                    ),
    	                    'hierarchical'      => true,
    	                    'show_ui'           => true,
    	                    'rewrite'           => array(
    	                        'slug'          => 'departamento',
    	                        'hierarchical'  => true,
    	                        'with_front'    => false
    	                    ),
    	                    'meta_box_cb'       => 'departamento_select_meta_box',
    	                );
    
    	                $taxonomy_departamento_args = apply_filters( 'taxonomy_departamento_args', $taxonomy_departamento_args);	                
    	                register_taxonomy( 'departamento', $postTypes, $taxonomy_departamento_args );
    
    	            // Select MetaBox
    	                function departamento_select_meta_box( $post, $box ) {
    	                    $defaults = array( 'taxonomy' => 'departamento' );
    
    	                    if ( ! isset( $box['args'] ) || ! is_array( $box['args'] ) ) {
    	                        $args = array();
    	                    } else {
    	                        $args = $box['args'];
    	                    }
    
    	                    $r        = wp_parse_args( $args, $defaults );
    	                    $tax_name = esc_attr( $r['taxonomy'] );
    	                    $taxonomy = get_taxonomy( $r['taxonomy'] );
    ?>
    	                    <div id="taxonomy-<?php echo $tax_name; ?>" class="categorydiv">
    	                        <div id="<?php echo $tax_name; ?>-all" class="tabs-panel">
    <?php
    	                            $name = ( $tax_name == 'departamento' ) ? 'post_category' : 'tax_input[' . $tax_name . ']';
    	                            echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks.
    ?>
    	                            <ul id="<?php echo $tax_name; ?>checklist" data-wp-lists="list:<?php echo $tax_name; ?>" class="categorychecklist form-no-clear">
    	                                <?php wp_terms_checklist( $post->ID, array( 'taxonomy' => $tax_name, 'checked_ontop' => false, 'walker' => new Walker_Checklist(), ) ); ?>
    	                            </ul>
    	                        </div>
    	                    </div>
    <?php
                    	}
                }
    
                // Columns Post Type
    	            function PostType_edit_columns( $columns ) {
    	                $columns['thumbnail'] 	 = __( 'Thumbnail' );
    	                $columns['departamento'] = __( 'Departamento' );
    	                $columns['galeria']   	 = __( 'Galeria' );
    	                $columns['visitas']   	 = __( 'Visitas' );
    	                return $columns;
    	            }
    
    	            function PostType_column_display( $PostType_columns, $post_id ) {
    	                switch ( $PostType_columns ) {
    	                    case 'thumbnail':
    	                        $width          = (int) 80;
    	                        $height         = (int) 80;
    	                        $thumbnail_id   = get_post_meta( $post_id, '_thumbnail_id', true );
    
    	                        // Display the featured image in the column view if possible
    	                        if ( $thumbnail_id ) {
    	                            $thumb = wp_get_attachment_image( $thumbnail_id, array( $width, $height ), true );
    	                        }
    	                        if ( isset( $thumb ) ) {
    	                            echo $thumb;
    	                        } else {
    	                            echo __( 'None' );
    	                        }
    	                    	break;
    
    	                    case 'departamento':
    	                        if ( $category_list     = get_the_term_list( $post_id, 'departamento', '', ', ', '' ) ) {
    	                            if ( is_admin() ) {
    	                                $terms          = get_the_terms( $post_id, 'departamento' );
    	                                foreach ( $terms as $term) {
    	                                    $term_padre = $term->parent;
    	                                }
    	                                $term_father    = get_term_by( 'id', $term_padre, 'departamento' );
    	                                echo $term_father->name . ' - ' . $category_list;
    	                            } else {
    	                                echo $category_list;
    	                            }
    	                        } else {
    	                            echo __( 'None' );
    	                        }
    	                    	break;
    
    	                    case 'galeria':
    
    	                        $post_id = get_the_id();
    	                        if ( $post_id ) {
    	                            echo $post_id;
    	                        } else {
    	                            echo __( 'None' );
    	                        }
    	                    	break;
    
    	                    case 'visitas':
    	                        $post_id    = get_the_id();
    	                        $count_key  = 'post_views_count';
    	                        $count      = get_post_meta( $post_id, $count_key, true );
    	                        echo $count;
    	                    	break;
    	                }
    	            }
    
                // Filtro Departamentos
    	            function add_taxonomy_filters() {
    	                global $typenow, $current_user;
    	                get_currentuserinfo();
    
    	                // An array of all the taxonomyies you want to display. Use the taxonomy name or slug
    	                $taxonomies = array( 'departamento' );
    
    	                // must set this to the post type you want the filter(s) displayed on
    	                if ( $typenow == 'proyecto' || $typenow == 'noticia' ) {
    	                    $permisos = of_get_option( $current_user->id . 'permisos' );
    
    	                    foreach ( $taxonomies as $tax_slug ) {
    	                        $current_tax_slug   = isset( $_GET[$tax_slug] ) ? $_GET[$tax_slug] : false;
    	                        $tax_obj            = get_taxonomy( $tax_slug );
    	                        $tax_name           = $tax_obj->labels->name;
    	                        $terms              = get_terms( 'departamento', array( 'post_type' => $typenow, 'fields' => 'all' ) );
    
    	                        if ( count( $terms ) > 0 ) {
    	                            echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
    	                            echo "<option value=''>$tax_name</option>";
    
    	                            foreach ( $terms as $term ) {
    	                                if ( $permisos[$term->term_id] == '1' || $current_user->roles[0] == 'administrator' ) {
    	                                    echo '<option style="font-weight: bold;" value=' . $term->slug, $current_tax_slug == $term->slug ? ' selected="selected"' : '','>' . $term->name . ' ( ' . $term->count .')</option>';
    	                                    $parent = $term->term_id;
    	                                } else {
    	                                    $term_parent = get_term_top_most_parent( $term->term_id, 'departamento' );
    	                                    if ( $parent == $term_parent['parent'] ) {
    	                                            switch ( $term_parent['contador'] ) {
    	                                                case '1':
    	                                                    $estilo = 'color: red';
    	                                                    break;
    
    	                                                case '2':
    	                                                    $estilo = 'color: green';
    	                                                    break;
    	                                            }
    
    	                                        echo '<option style="' . $estilo . '" value=' . $term->slug, $current_tax_slug == $term->slug ? ' selected="selected"' : '','>' . $term->name . ' ( ' . $term->count .')</option>';
    	                                    }
    	                                }
    	                            }
    	                            echo "</select>";
    	                        }
    	                    }
    	                }
    	            }
            }
        }
        new PostType;

    Todo lo relacionado con rewrite rules:

    // Rewrites rules Noticias
           	add_action( 'generate_rewrite_rules', 'register_PostType_rewrite_rules' );
            function register_PostType_rewrite_rules( $wp_rewrite ) {
                $new_rules = array( 
                    PostType_lang_rewrite('proyecto') . '/([^/]+)/?$' => 'index.php?departamento=' . $wp_rewrite->preg_index( 1 ),
                    PostType_lang_rewrite('proyecto') . '/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&departamento=' . $wp_rewrite->preg_index( 1 ) . '&proyecto=' . $wp_rewrite->preg_index( 2 ),
                    PostType_lang_rewrite('proyecto') . '/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=proyecto&departamento=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ),
                    PostType_lang_rewrite('proyecto') . '/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&departamento=' . $wp_rewrite->preg_index( 2 ) . '&proyecto=' . $wp_rewrite->preg_index( 3 ),
                    PostType_lang_rewrite('proyecto') . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&departamento=' . $wp_rewrite->preg_index( 3 ) . '&proyecto=' . $wp_rewrite->preg_index( 4 ),
    
                    PostType_lang_rewrite('noticia') . '/([^/]+)/?$' => 'index.php?departamento=' . $wp_rewrite->preg_index( 1 ),
                    PostType_lang_rewrite('noticia') . '/([^/]+)/([^/]+)/?$' => 'index.php?post_type=noticia&departamento=' . $wp_rewrite->preg_index( 1 ) . '&noticia=' . $wp_rewrite->preg_index( 2 ),
                    PostType_lang_rewrite('noticia') . '/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=noticia&departamento=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ),
                    PostType_lang_rewrite('noticia') . '/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=noticia&departamento=' . $wp_rewrite->preg_index( 2 ) . '&noticia=' . $wp_rewrite->preg_index( 3 ),
                    PostType_lang_rewrite('noticia') . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=noticia&departamento=' . $wp_rewrite->preg_index( 3 ) . '&noticia=' . $wp_rewrite->preg_index( 4 ),
                );
    
                $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
            }
    
            // A hacky way of adding support for flexible custom permalinks
            // There is one case in which the rewrite rules from register_kb_rewrite_rules() fail:
            // When you visit the archive page for a child section(for example: http://example.com/noticia/category/child-category)
            // The deal is that in this situation, the URL is parsed as a Knowledgebase post with slug "child-category" from the "category" section
            function fix_PostType_subcategory_query($query) {
            	$postTypes = array( 'proyecto', 'noticia' );
    
            	foreach ( $postTypes as $postType ) {
    	            if ( isset( $query['post_type'] ) && $postType == $query['post_type'] ) {
    	                if ( isset( $query[$postType] ) && $query[$postType] && isset( $query['departamento'] ) && $query['departamento'] ) {
    	                    $query_old = $query;
    	                    // Check if this is a paginated result(like search results)
    	                    if ( 'page' == $query['departamento'] ) {
    	                        $query['paged'] = $query['name'];
    	                        unset( $query['departamento'], $query['name'], $query[$postType] );
    	                    }
    	                    // Make it easier on the DB
    	                    //$query['fields'] = 'ids';
    	                    $query['posts_per_page'] = 1;
    
    	                    // See if we have results or not
    	                    $_query = new WP_Query( $query );
    	                    if ( ! $_query->posts ) {
    	                        $query = array( 'departamento' => $query[$postType] );
    	                        if ( isset( $query_old['departamento'] ) && 'page' == $query_old['departamento'] ) {
    	                            $query['paged'] = $query_old['name'];
    	                        }
    	                    }
    	                }
    	            }
    	        }
    
                return $query;
            }
            add_filter( 'request', 'fix_PostType_subcategory_query', 10 );
    
            function PostType_article_permalink( $article_id, $section_id = false, $leavename = false, $only_permalink = false ) {
                $taxonomy   = 'departamento';
                $article    = get_post( $article_id );
    
                $return     = '<a href="';
                $permalink  = ( $section_id ) ? trailingslashit( get_term_link( intval( $section_id ), 'departamento' ) ) : home_url( '/' . PostType_lang_rewrite(get_post_type()) . '/' );
                $permalink .= trailingslashit( ( $leavename ? "%$article->post_type%" : $article->post_name ) );
                $return    .= $permalink . '/" >' . get_the_title( $article->ID ) . '</a>';
                return ( $only_permalink ) ? $permalink : $return;
            }
    
            function filter_PostType_post_link( $permalink, $post, $leavename ) {
                if ( get_post_type( $post->ID ) == 'proyecto' || get_post_type( $post->ID ) == 'noticia' ) {
                    $terms      = wp_get_post_terms( $post->ID, 'departamento' );
                    $term       = ( $terms ) ? $terms[0]->term_id : false;
                    $permalink  = PostType_article_permalink( $post->ID, $term, $leavename, true );
                }
                return $permalink;
            }
            add_filter( 'post_type_link', 'filter_PostType_post_link', 100, 3 );
    
            function filter_PostType_section_terms_link( $termlink, $term, $taxonomy = false ) {
                if ( $taxonomy == 'departamento' ) {
                    $section_ancestors = get_ancestors( $term->term_id, $taxonomy );
                    krsort( $section_ancestors );
                    $termlink =  home_url( '/' . PostType_lang_rewrite(get_post_type()) . '/' );
                    foreach ( $section_ancestors as $ancestor ) {
                        $section_ancestor = get_term( $ancestor, $taxonomy );
                        $termlink .= $section_ancestor->slug . '/';
                    }
                    $termlink .= trailingslashit( $term->slug );
                }
    
                return $termlink;
            }
            add_filter( 'term_link', 'filter_PostType_section_terms_link', 100, 3 );
    
        // Traducir la url en castellano o ingles, noticia o new
            function PostType_lang_rewrite($posttype) {
                // IDIOMA
                    $blog   = MslsBlogCollection::instance()->get_current_blog();
                    $idioma = $blog->get_description();
    
                // VARIABLES
                    if ( $idioma == 'ES' ) {
                    	if ( $posttype == 'proyecto' ) {
                    		$clave = 'proyecto';
                    	} else {
                    		$clave = 'noticia';
                    	}
                    } else {
                    	if ( $posttype == 'proyecto' ) {
                    		$clave = 'project';
                    	} else {
                    		$clave = 'new';
                    	}
                    }
    
                return $clave;
            }
    
        // Traducir la url en castellano o ingles, noticia o new
            function PostType_options_get_permalink( $url, $language ) {
                if ( 'us' == $language ) {
                	$url = str_replace( '/proyecto/', '/project/', $url );
                    $url = str_replace( '/noticia/', '/new/', $url );
                } else {
                	$url = str_replace( '/project/', '/proyecto/', $url );
                    $url = str_replace( '/new/', '/noticia/', $url );
                }
    
                return $url;
            }
            add_filter( 'msls_options_get_permalink', 'PostType_options_get_permalink', 10, 2 );

    En el header.php llamo así al menu:

    <nav class="menu_principal_departamentos">
                        <ul>
    <?php
                            $terms = get_terms( 'departamento', array( 'hide_empty' => 0, 'parent' => 0, 'post_type' => 'proyecto' ) );
                            foreach ( $terms as $term ) {                            
                                    $url = get_bloginfo( 'url' ) . '/proyecto/' . $term->slug . '/';
    ?>
                                    <li class="<?php echo $term->slug; ?>"><a href="<?php echo $url; ?>"><?php echo $term->name; ?></a></li>
    <?php
                            }
    ?>
                        </ul>
                    </nav>

    Y por ultimo en taxonomy-departamento.php:

    <?php
    	get_header();
    
    	// IDIOMA
    		$blog 		= MslsBlogCollection::instance()->get_current_blog();
    		$idioma 	= $blog->get_description();
    
    	// VARIABLES
    		if ( $idioma == 'ES' ) {
    			$buscar = 'BUSCAR';
    			$ver 	= 'VER PROYECTOS';
    		} else {
    			$buscar = 'SEARCH';
    			$ver	= 'GO TO PROJECTS';
    		}
    
    	// Saber por la url el post type
    		$uri = explode( '/', $_SERVER['REQUEST_URI'] );
    		switch ( $uri[2] ) {
    			case 'proyecto':
    				$PostType = 'proyecto';
    				break;
    
    			case 'noticia':
    				$PostType = 'noticia';
    				break;
    		}
    ?>
    	<article>
    		<div class="pr_content">
    <?php
    			if ( $PostType == 'proyecto' ) {
    				global $wp_query;
    				$taxonomy 					= $wp_query->queried_object;
    				$taxonomy->children 		= get_terms( 'departamento', array( 'hide_empty' => 0, 'parent' => $taxonomy->term_id, 'orderby' => 'id', 'order' => 'ASC', 'post_type' => 'proyecto' ) );
    				$parent						= $taxonomy->parent;
    				$not_the_last_subcategory 	= is_array( $taxonomy->children ) && count( $taxonomy->children ) && $taxonomy->parent == 0;
    
    				if ( $parent ) { // Ficha Subcategoria
    
    				} else {  // Ficha Categoria
    
    				}
    
    				if ( $not_the_last_subcategory ) { // MOSTRAR LAS SUBCATEGORIAS
    					$columnas = count($taxonomy->children);
    ?>
    					<div class="pr_linea"></div>
    					<div class="pr_subcategorias <?php echo 'col' . $columnas; ?>">
    <?php
    						foreach ( $taxonomy->children as $key=>$subcategory ) {
    ?>
    							<div class="th_subcategoria">
    								<h2><a href="<?php echo get_term_link( $subcategory, 'departamento' ) ?>"><?php echo $subcategory->name ?></a></h2>
    								<p class="th_subcategoria_description"><a href="<?php echo get_term_link( $subcategory, 'departamento' ) ?>">
    <?php 
    									$description = $subcategory->description;
    									echo $description;
    ?>
    								</a></p>
    								<p class="th_subcategoria_gotoprojects"><a href="<?php echo get_term_link( $subcategory, 'departamento' ) ?>"><?php echo $ver; ?></a></p>
    							</div>
    <?php
    						}
    ?>
    					</div>
    <?php
    				} else { // MOSTRAR LOS PROYECTOS DE LAS SUBCATEGORIAS
    					$taxonomy->children = get_terms( 'departamento', array( 'hide_empty' => 0, 'parent' => $parent, 'orderby' => 'id', 'order' => 'ASC', ) );
    					$columnas  			= count($taxonomy->children);
    					$current_category 	= get_query_var('departamento');
    ?>
    					<div class="pr_subcategorias_menu <?php echo 'col' . $columnas; ?>">
    <?php
    						$term = get_term( $parent, 'departamento' );
    ?>
    						<h1><span><?php echo $term->name; ?></span><span class="rotate1" id="down-icon"></span></h1>
    						<ul>
    <?php
    							foreach ( $taxonomy->children as $key=>$subcategory ) {
    ?>
    								<li class="th_subcategoria <?php if ( $subcategory->slug == $current_category ) echo 'activo'; ?>"><a href="<?php echo get_term_link( $subcategory, 'departamento' ) ?>"><?php echo $subcategory->name ?></a></li>
    <?php
    							}
    ?>
    							<li class="clear"></li>
    						</ul>
    					</div>
    					<div class="pr_mosaico e_categorias">
    <?php 
    						$loop = new WP_Query( 
    							array(
    								'departamento' 		=> $current_category,
    								'post_type' 		=> 'proyecto',
    								'posts_per_page' 	=> -1,
    								'orderby' 			=> 'menu_order',
    								'order' 			=> 'ASC',
    								'no_found_rows' 	=> true // Si no hay paginacion, hace mas rapido la QUERY
    							)
    						);
    
    						if ( $loop->have_posts() ) {
    							while ( $loop->have_posts() ) {
    								$loop->the_post();
    
    								$pr_id 		= get_the_id();
    								$pr_image 	= wp_get_attachment_url( get_post_thumbnail_id( $pr_id ) );
    ?>
    								<div class="th_proyecto">
    									<a href="<?php the_permalink(); ?>"><img src="<?php //echo aq_resize( $pr_image, 425, 217, false ); ?>" alt="<?php the_title(); ?>" /></a>
    									<h2><a href="<?php the_permalink(); ?>"><span><?php the_title(); ?></span></a></h2>
    								</div>
    <?php
    							}
    						}
    ?>
    					</div>
    <?php
    				}
    			} else {
    ?>
    				NOTICIAS
    <?php
    			}
    ?>
    		</div>
    	</article>
    	
    <?php
    	get_footer();
    ?>

    Funcionar me funciona todo bien, pero a mi detectar a través de la url en que post type me parece un poco chapuza, querría detectarlo de forma normal

    Espero que se vea todo bien, saludos

    Iniciador del debate inigonz

    (@inigonz)

    En los rewrites rules, en la primera linea:
    PostType_lang_rewrite('proyecto') . '/([^/]+)/?$' => 'index.php?departamento=' . $wp_rewrite->preg_index( 1 ),
    he añadido el posttype quedando asi:
    PostType_lang_rewrite('proyecto') . '/([^/]+)/?$' => 'index.php?post_type=proyecto&departamento=' . $wp_rewrite->preg_index( 1 ),
    y me lo reconoce bien, pero en los hijos aun teniendo el posttype en el rewrite no lo reconoce, alguna idea?

    Gracias

    Moderador kallookoo

    (@kallookoo)

    Hola,
    No entiendo que quieres hacer, por norma el archivo-taxonomy.php te mostrara todos los post que tenga la taxonomy independientemente del post type, igualmente dentro del loop si usas get_post_type(); te deberia mostrar el nombre.

    Que es exactamente lo que quieres hacer? Un archivo de taxonomy o de post type?

    Iniciador del debate inigonz

    (@inigonz)

    Buenas Kallookoo,

    Te explico, tengo unas categorías principales, en este caso departamentos, cada departamento puede tener hijos y estos hijos pueden tener mas hijos. Los proyectos siempre pertenecen a un ultimo hijo, las noticias a un departamentos y ahora añado publicaciones que pueden pertenecer a un departamento, o a un ultimo hijo.(puedo tener un cat1 y un cat2 con hijo cat2.2, los últimos hijos serian cat1 y cat2.2, no se si me explico).

    En el menú tengo los departamentos, cuando accedo a un dpto. veo la vista de los hijos de este dpto, y cuando accedo a un hijo, veo los proyectos de ese hijo, y ya si pincho en el proyecto veo el proyecto. A las noticias directamente veo las noticias del dpto y las publicaciones veria directamente las publicaciones del dpto, o del ultimo hijo.

    En mi taxonomy-dpto compruebo que post type tiene y dependiendo de cual sea, si es proyecto y tiene hijos, muestro una vista, si es hijo tengo un neq query filtrado los post por ese hijo y el post type.

    No se si me he explicado bien, y no se si lo estoy haciendo correctamente. Gracias

    Moderador kallookoo

    (@kallookoo)

    Creo que esto te puede orientar: https://wordpress.stackexchange.com/a/117050
    Lamento no darte mas ayuda pero sigo sin comprender tu problema…

    Iniciador del debate inigonz

    (@inigonz)

    Muchas gracias kallookoo, lo voy a revisar.
    El problema que tengo, es que si hago un get_post_type() en el comienzo de taxonomy-departamentos.php, no me dice correctamente que post type es, ya que la url indica otro post type. Para sacar el post type correcto, compruebo en la uri que post type tiene, pero no se si es la manera correcta o hay una forma mejor.
    Yo en taxonomy-departamentos no pongo el loop, no se si es necesario, pero igual me falla por eso.

    Es decir, si yo estoy viendo esta url: http://localhost/wp-multisite/noticia/dpto-1/dpto-1-5/ (postype/term/termhijo) me dice con get_post_type() que es un proyecto, cuando deberia decirme que es una noticia, no? no se si me explico mejor

Viendo 9 respuestas - de la 1 a la 9 (de un total de 9)
  • El debate ‘Varios Post Type con la misma taxonomia’ está cerrado a nuevas respuestas.