Respuestas de foro creadas

Viendo 15 respuestas - de la 31 a la 45 (de un total de 55)
  • Na, aquí estamos para ayudarnos entre todos, a mi este tema también me costo sacarlo

    saludos

    Iniciador del debate inigonz

    (@inigonz)

    Buenas Merksk8,

    Has podido mirar algo por la red o has conseguido resolverlo?
    yo sigo buscando pero no encuentro nada de na, tengo mas paginas vistas ….. y todas dan las mismas soluciones, que si el flush_rewrite_rules(), y cosas así, y a la gente le suele funcionar o eso ponen, pero a mi na de na, ya empiezo a pensar que tengo algo mal en mi código, no se

    Saludos

    Buenas,

    El ajax en wp funciona de forma distinta a como se utiliza en una web normal.
    Mi codigo js donde tengo el ajax:

    var formDatos = new FormData();
                    formDatos.append( 'email', jQuery('input[name="email"]').val() );
                    formDatos.append( 'contrasena', jQuery('input[name="contrasena"]').val() );
    
                    jQuery.ajax({
                        url: 'mi-web/wp-admin/admin-ajax.php?action=formEntrarUsuario',
                        type: 'POST',
                        contentType: false,
                        data: formDatos,
                        processData: false,
                        cache: false,
                        dataType: 'text', // what to expect back from the PHP script, if anything
                        success: function(datos) {
                            if ( datos == 0 ) {
                                jQuery('.msg').html('El email o contraseña no existen');
                                jQuery('input[type="password"], input[type="text"]').addClass('bad');
                                jQuery('input[type="text"]').focus();
                            } else {
                                window.location.replace(datos);
                            }
                        }
                    });

    Y luego tienes que poner la funcion a la que llamas, ya puedas ponerla en el functions o en un archivo aparte antes declarado.

    function formEntrarUsuario() {
                global $wpdb;
    
                $email      = $_POST['email'];
                $contrasena = $_POST['contrasena'];
                $user       = $wpdb->get_results('SELECT * FROM usuarios WHERE email ="' . $email . '"');
    
                if ( $wpdb->num_rows ) {
                    if ( password_verify( $contrasena, $user[0]->contrasena ) ) {
                        session_start();
                        $_SESSION['user'] = $user[0]->id;
                        echo get_site_url() . '/newsletters/';
                    } else {
                        echo '0';
                    }
                } else {
                    echo '0';
                }
    
                die();
            }
            add_action( 'wp_ajax_formEntrarUsuario', 'formEntrarUsuario' );
            add_action( 'wp_ajax_nopriv_formEntrarUsuario', 'formEntrarUsuario' );

    La url del ajax siempre tiene que poner lo mismo hasta el action que es donde pones tu funcion.
    La funcion que llamas siempre tiene que tener las dos acciones, una para dentro del admin y otra para lo publico.

    Si no es así, que alguien me corrija, pero a mi me funciona esto perfectamente.

    Saludos

    • Esta respuesta fue modificada hace 7 años, 1 mes por inigonz.
    Iniciador del debate inigonz

    (@inigonz)

    oki, muchísimas gracias por tu ayuda, por tu tiempo, da gusto escribir en un foro y la gente sea tan maja, ayude tanto, y se implique de esta manera, muchísimas gracias.
    Si saco algo en claro, te comento

    Saludos

    Iniciador del debate inigonz

    (@inigonz)

    el taxonomy-{taxonomy} funciona bien, el que me falla es el single-{post-type} que me sale la pantalla vacía, si renombro el archivo y pongo solo single.php sale la ficha del proyecto bien, pero necesito que sea single-{post-type}.

    Proyectos es el único post type que tiene categorías, padres, hijas y algunas nietas, las demás solo tienen categorías, es decir, por ejemplo el dpto de energía tiene en «proyectos», la categoría energía, como hijos tiene termosolares, eólica, biomasa,.. y a su vez, termosolares tiene como hijos ciclos combinados, ciclos combinado simples,….
    en noticias solo tiene la categoría de energía, lo mismo pasará en publicaciones, no se si me explico.

    Me parece demasiado «rollo» hacer todo esto para poner unas urls que en la mayoría de las webs funcionan así, porque wp no lo hace por defecto?

    Muchas gracias por todo.

    Iniciador del debate inigonz

    (@inigonz)

    en mi plantilla taxonomy-proyecto-category.php:

    <?php
    	get_header();
    
    	if ( qtrans_getLanguage() == 'en' ) {
            $idioma = 'en';
        } else {
            $idioma = 'es';
        }
    
    	global $wp_query;
        $taxonomy           		= $wp_query->queried_object;
        $taxonomy->children 		= get_terms( 'proyecto-category', array( 'hide_empty' => 0, 'parent' => $taxonomy->term_id, 'orderby' => 'id', 'order' => 'ASC', ) );
        $parent             		= $taxonomy->parent;
        $not_the_last_subcategory 	= is_array( $taxonomy->children ) && count( $taxonomy->children ) && $taxonomy->parent == 0;
    ?>
        <section>
            <div class="pr_content">
    <?php 
                if ( $parent ) { // Ficha Subcategoria
    
                } else {  // Ficha Categoria
    
                }
    
                if ( $not_the_last_subcategory ) { // MOSTRAR LAS SUBCATEGORIAS
                	$columnas = count($taxonomy->children);
    ?>
    				<div class="p_fondo"><span style="background-image: url('../uploads/2016/04/DKIST-ADA-Home-.jpg')"></span></div>
                    <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, 'proyecto-category' ) ?>"><?php echo $subcategory->name ?></a></h2>
                                <p class="th_subcategoria_description"><a href="<?php echo get_term_link( $subcategory, 'proyecto-category' ) ?>">
    <?php 
                                    $description = qtrans_use( $idioma, $subcategory->description, false );
                                    echo $description;
    ?>
                                </a></p>
                                <p class="th_subcategoria_gotoprojects"><a href="<?php echo get_term_link( $subcategory, 'proyecto-category' ) ?>"><?php if ( $idioma == 'es' ) { echo 'VER PROYECTOS'; } else { echo 'GO TO PROJECTS'; } ?></a></p>
                            </div>
    <?php
                        }
    ?>
                    </div>
    <?php
                } else { // MOSTRAR LOS PROYECTOS DE LAS SUBCATEGORIAS
                	$taxonomy->children = get_terms( 'proyecto-category', array('hide_empty' => 0, 'parent' => $parent, 'orderby' => 'id', 'order' => 'ASC', ));
                	$columnas  			= count($taxonomy->children);
                	$current_category 	= get_query_var('proyecto-category');
    ?>
    				<div class="pr_subcategorias_menu <?php echo 'col' . $columnas; ?>">
    <?php
                        $term = get_term( $parent, 'proyecto-category' );
    ?>
                        <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, 'proyecto-category' ) ?>"><?php echo $subcategory->name ?></a></li>
    <?php
                        	}
    ?>
    						<li class="clear"></li>
    					</ul>
    				</div>
    				<div class="pr_mosaico">
    <?php 
    					$loop = new WP_Query( 
                            array(
                                'proyecto-category' => $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">
                                    <img src="<?php echo aq_resize( $pr_image, 425, 217, false ); ?>" alt="<?php the_title(); ?>" />
                                    <h2><a href="<?php the_permalink(); ?>"><span><?php the_title(); ?></span></a></h2>
                                </div>
    <?php
                            }
                        }
    ?>
    				</div>
    <?php
                }
    ?>
    		</div>
        </section>
    <?php
    	get_footer();
    ?>

    Y en el single-proyecto.php:

    <?php
    	get_header();
    
    	if ( qtrans_getLanguage() == 'en' ) {
    		$idioma = 'en';
    	} else {
    		$idioma = 'es';
    	}
    ?>
    	<section>
    		<div class="pr_content">
    <?php
    			$post_id 			= get_the_id();
    			$term 	 			= wp_get_object_terms( $post_id, 'proyecto-category' );
    			$current_category 	= $term[0]->slug;
    			$current_father 	= $term[0]->parent;
    			$taxonomy->children = get_terms( 'proyecto-category', array( 'hide_empty' => 0, 'parent' => $current_father, 'orderby' => 'id', 'order' => 'ASC', ));
    			$columnas			= count($taxonomy->children);
    ?>
    			<div class="pr_subcategorias_menu <?php echo 'col' . $columnas; ?>">
    				<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, 'proyecto-category' ) ?>"><?php echo $subcategory->name ?></a></li>
    <?php
    					}
    ?>
    					<li class="clear"></li>
    				</ul>
    			</div>
    			<div class="pr_proyecto">
    <?php
    				if ( have_posts() ) {
    					while ( have_posts() ) {
    						the_post();
    
    						include ( get_template_directory() . '/php/slide.php' );
    ?>
    						<h1><?php the_title(); ?></h1>
    						<div class="pr_contenido">
    							<div>
    								<div class="izq">
    									<?php $client = 'Cliente'; ?>
    									<?php if ( $client ) { ?> <p><span>CLIENTE:</span> </p> <?php } ?>
    									<?php if ( $services ) { ?> <p><span>SERVICIOS:</span> </p> <?php } ?>
    									<?php if ( $year ) { ?> <p><span>AÑO:</span> </p> <?php } ?>
    									<?php if ( $country ) { ?> <p><span>PAIS:</span> </p> <?php } ?>
    								</div>
    								<div class="dcha <?php if ( !$client && !$services && !$year && !$country ) echo 'full'; ?>">
    									<?php the_excerpt(); ?>
    								</div>
    								<div class="clear"></div>
    							</div>
    <?php
    							if ( get_the_content() || $pdf || $relaciones || $premios || $videos ) {
    ?>
    								<div class="pr_mas_botones">
    									<ul>
    										<li class="btn_icono"></li>
    										<?php if ( get_the_content() ) { ?> <li class="btn_mas">INFO</li> <?php } ?>
    										<?php if ( $relaciones ) { ?> <li class="btn_relaciones">PROYECTOS RELACIONADOS</li> <?php } ?>
    										<?php if ( $premios ) { ?> <li class="btn_premios">PREMIOS</li> <?php } ?>
    										<?php if ( $videos ) { ?> <li class="btn_videos">VIDEOS</li> <?php } ?>
    									</ul>
    								</div>
    								<div class="pr_mas_contenido">
    <?php
    									if ( get_the_content() ) echo '<div class="cnt_mas">' . get_the_content() . '</div>';
    									if ( $relaciones ) 		 echo '<div class="cnt_relaciones">' . $relaciones . '</div>';
    									if ( $premios ) 		 echo '<div class="cnt_premios">' . $premios . '</div>';
    									if ( $videos )  		 echo '<div class="cnt_videos">' . $videos . '</div>';
    ?>
    								</div>
    <?php
    							}
    ?>
    						</div>
    <?php
    					}
    				}
    ?>
    			</div>
    <?php
    			$father = get_term_by( 'id', $current_father, 'proyecto-category' );
    ?>
    			<h3><?php echo $father->name . ' - ' . $current_category; ?></h3>
    			<div class="pr_mosaico">
    <?php 
    				$loop = new WP_Query( 
    					array(
    						'proyecto-category' => $current_category,
    						'post_type'        	=> 'proyecto',
    						'post__not_in'      => array( $post_id ),
    						'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">
    							<img src="<?php echo aq_resize( $pr_image, 425, 217, false ); ?>" alt="<?php the_title(); ?>" />
    							<h2><a href="<?php the_permalink(); ?>"><span><?php the_title(); ?></span></a></h2>
    						</div>
    <?php
    					}
    				}
    ?>
    			</div>
    		</div>
    	</section>
    <?php
    	get_footer();
    ?>

    Si necesitas alguna pagina mas me dices, pero si, he reseteado permalinks, he probado con lo de flush dns y no me reconoce el single-proyecto y no se porque, las urls funcionan perfectamente

    Gracias

    Iniciador del debate inigonz

    (@inigonz)

    En el functions.php, abajo tengo las funciones de ayer para poder poner bien las urls:

    add_action( 'generate_rewrite_rules', 'register_proyecto_rewrite_rules' );
            function register_proyecto_rewrite_rules( $wp_rewrite ) {
                $new_rules = array( 
                    'proyecto/([^/]+)/?$' => 'index.php?proyecto-category=' . $wp_rewrite->preg_index( 1 ),
                    'proyecto/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&proyecto-category=' . $wp_rewrite->preg_index( 1 ) . '&proyecto=' . $wp_rewrite->preg_index( 2 ),
                    'proyecto/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=proyecto&proyecto-category=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ),
                    'proyecto/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&proyecto-category=' . $wp_rewrite->preg_index( 2 ) . '&proyecto=' . $wp_rewrite->preg_index( 3 ),
                );
    
                $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/proyecto/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_proyecto_subcategory_query($query) {
                if ( isset( $query['post_type'] ) && 'proyecto' == $query['post_type'] ) {
                    if ( isset( $query['proyecto'] ) && $query['proyecto'] && isset( $query['proyecto-category'] ) && $query['proyecto-category'] ) {
                        $query_old = $query;
                        // Check if this is a paginated result(like search results)
                        if ( 'page' == $query['proyecto-category'] ) {
                            $query['paged'] = $query['name'];
                            unset( $query['proyecto-category'], $query['name'], $query['proyecto'] );
                        }
                        // 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( 'proyecto-category' => $query['proyecto'] );
                            if ( isset( $query_old['proyecto-category'] ) && 'page' == $query_old['proyecto-category'] ) {
                                $query['paged'] = $query_old['name'];
                            }
                        }
                    }
                }
    
                return $query;
            }
            add_filter( 'request', 'fix_proyecto_subcategory_query', 10 );
    
            function proyecto_article_permalink( $article_id, $section_id = false, $leavename = false, $only_permalink = false ) {
                $taxonomy = 'proyecto-category';
                $article = get_post( $article_id );
    
                $return = '<a href="';
                $permalink = ( $section_id ) ? trailingslashit( get_term_link( intval( $section_id ), 'proyecto-category' ) ) : home_url( '/proyecto/' );
                $permalink .= trailingslashit( ( $leavename ? "%$article->post_type%" : $article->post_name ) );
                $return .= $permalink . '/" >' . get_the_title( $article->ID ) . '</a>';
                return ( $only_permalink ) ? $permalink : $return;
            }
    
            function filter_proyecto_post_link( $permalink, $post, $leavename ) {
                if ( get_post_type( $post->ID ) == 'proyecto' ) {
                    $terms = wp_get_post_terms( $post->ID, 'proyecto-category' );
                    $term = ( $terms ) ? $terms[0]->term_id : false;
                    $permalink = proyecto_article_permalink( $post->ID, $term, $leavename, true );
                }
                return $permalink;
            }
            add_filter( 'post_type_link', 'filter_proyecto_post_link', 100, 3 );
    
            function filter_proyecto_section_terms_link( $termlink, $term, $taxonomy = false ) {
                if ( $taxonomy == 'proyecto-category' ) {
                    $section_ancestors = get_ancestors( $term->term_id, $taxonomy );
                    krsort( $section_ancestors );
                    $termlink =  home_url( '/proyecto/' );
                    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_proyecto_section_terms_link', 100, 3 );
    Iniciador del debate inigonz

    (@inigonz)

    buenas,

    No se si te referirás a esto, pero ahora mismo tengo creados diferentes custom post type,
    proyecto
    noticia
    publicación
    oficina
    ….

    cada uno tiene su custom taxonomy, {post-type}-category.

    En mi caso, no utilizo la plantilla archive, ni la general, ni singular, cada custom post type, tiene su plantilla taxonomy-{taxonomy} y su single-{post-type}, ya que cada una tiene diferentes vistas.

    He creado un archivo donde creo el post type de proyectos, con el código del post de ayer, lo tengo así:

    if ( !class_exists( 'Proyectos_post_type' ) ) {
    
            class Proyectos_post_type {
    
                function __construct() {
                    // Adds the proyecto post type and taxonomies
                    add_action( 'init', array( &$this, 'proyecto_init' ), 0 );
    
                    // Adds columns in the admin view for thumbnail and taxonomies
                    add_filter( 'manage_edit-proyecto_columns', array( &$this, 'proyecto_edit_columns' ) );
                    add_action( 'manage_posts_custom_column', array( &$this, 'proyecto_column_display' ), 10, 2 );
    
                    // Allows filtering of posts by taxonomy in the admin view
                    add_action( 'restrict_manage_posts', array( &$this, 'proyecto_add_taxonomy_filters' ) );
                }
    
                function proyecto_init() {
    
                    /*
                     * Enable the Proyecto custom post type
                     * http://codex.wordpress.org/Function_Reference/register_post_type
                     */
    
                    $labels = array(
                        'name'                  => __( 'Proyectos' ),
                        'singular_name'         => __( 'Proyecto' ),
                        'add_new'               => __( 'Añadir nuevo' ),
                        'add_new_item'          => __( 'Añadir nuevo Proyecto' ),
                        'edit_item'             => __( 'Editar Proyecto' ),
                        'new_item'              => __( 'Nuevo Proyecto' ),
                        'view_item'             => __( 'Ver Proyecto' ),
                        'search_items'          => __( 'Buscar Proyecto' ),
                        'not_found'             => __( 'No se encontraron Proyectos' ),
                        'not_found_in_trash'    => __( 'No se encontraron Proyectos 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', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ),
                        'hierarchical'          => false,
                        'has_archive'           => 'proyecto',
                        'rewrite'               => array(
                            'slug'              => 'proyecto-item',
                            'hierarchical'      => true,
                            'with_front'        => false
                        )
                    );
    
                    $args = apply_filters( 'proyecto_args', $args);
                    
                    register_post_type( 'proyecto', $args );
    
                    /*
                     * Register a taxonomy for Proyectos Categories
                     * http://codex.wordpress.org/Function_Reference/register_taxonomy
                     */
    
                    // Registrar las categorias de proyectos
                    $taxonomy_proyecto_category_labels = array(
                        'name'                       => __( 'Categorias de Proyectos'),
                        'singular_name'              => __( 'Categoria de Proyectos'),
                        'search_items'               => __( 'Buscar la Categoria de Proyectos'),
                        'popular_items'              => __( 'Categorias de Proyectos Populares'),
                        'all_items'                  => __( 'Todas las Categoria de Proyectos'),
                        'parent_item'                => __( 'Padre de la Categoria de Proyectos'),
                        'parent_item_colon'          => __( 'Padre de la Categoria de Proyectos:'),
                        'edit_item'                  => __( 'Editar la Categoria de Proyectos' ),
                        'update_item'                => __( 'Actualizar la Categoria de Proyectos' ),
                        'add_new_item'               => __( 'Añadir nueva Categoria de Proyectos' ),
                        'new_item_name'              => __( 'Nueva Categoria de Proyectos' ),
                        'separate_items_with_commas' => __( 'Separar las Categorias de Proyectos por comas' ),
                        'add_or_remove_items'        => __( 'Añadir o Borrar Categoria de Proyectos' ),
                        'choose_from_most_used'      => __( 'Elegir entre las Categorias de Proyectos mas usadas' ),
                        'menu_name'                  => __( 'Categoria de Proyectos' ),
                    );
    
                    $taxonomy_proyecto_category_args = array(
                        'labels'             => $taxonomy_proyecto_category_labels,
                        'public'             => true,
                        'hierarchical'       => true,
                        'show_ui'            => true,
                        'rewrite'            => array(
                            'slug'           => 'proyecto-category',
                            'hierarchical'   => true,
                            'with_front'     => false
                        ),
                    );
    
                    $taxonomy_proyecto_category_args = apply_filters( 'taxonomy_proyecto_category_args', $taxonomy_proyecto_category_args);
                    
                    register_taxonomy( 'proyecto-category', array( 'proyecto' ), $taxonomy_proyecto_category_args );
    
                    // Registrar los tags, proyectos relacionados, de proyectos
                    $taxonomy_proyecto_tag_labels = array(
                        'name'                       => __( 'Tags de Proyectos'),
                        'singular_name'              => __( 'Tag de Proyectos'),
                        'search_items'               => __( 'Buscar el Tag de Proyectos'),
                        'popular_items'              => __( 'Tags de Proyectos Populares'),
                        'all_items'                  => __( 'Todos los Tags de Proyectos'),
                        'parent_item'                => __( 'Padre del Tag de Proyectos'),
                        'parent_item_colon'          => __( 'Padre del Tag de Proyectos:'),
                        'edit_item'                  => __( 'Editar el Tag de Proyectos' ),
                        'update_item'                => __( 'Actualizar el Tag de Proyectos' ),
                        'add_new_item'               => __( 'Añadir nuevo Tag de Proyectos' ),
                        'new_item_name'              => __( 'Nuevo Tag de Proyectos' ),
                        'separate_items_with_commas' => __( 'Separar los Tags de Proyectos por comas' ),
                        'add_or_remove_items'        => __( 'Añadir o Borrar Tag de Proyectos' ),
                        'choose_from_most_used'      => __( 'Elegir entre los Tags de Proyectos mas usadas' ),
                        'menu_name'                  => __( 'Tag de Proyectos' ),
                    );
    
                    $taxonomy_proyecto_tag_args = array(
                        'labels'            => $taxonomy_proyecto_tag_labels,
                        'public'            => true,
                        'show_in_nav_menus' => true,
                        'show_ui'           => true,
                        'show_tagcloud'     => true,
                        'hierarchical'      => false,
                        'rewrite'           => array(
                            'slug'          => 'tags'
                        ),
                        'query_var'         => true
                    );
    
                    $taxonomy_proyecto_tag_args = apply_filters( 'taxonomy_proyecto_tag_args', $taxonomy_proyecto_tag_args);
                    
                    register_taxonomy( 'tag_proyectos', array( 'proyecto' ), $taxonomy_proyecto_tag_args );
                }
    
                /*
                 * Add Columns to Proyecto Edit Screen
                 * http://wptheming.com/2010/07/column-edit-pages/
                 */
    
                function proyecto_edit_columns( $columns ) {
                    //$columns['proyecto_thumbnail']  = __( 'Thumbnail' );
                    $columns['proyecto_category']   = __( 'Category' );
                    //$columns['tag_proyectos']       = __( 'Tag' );
                    //$columns['galeria_proyectos']   = __( 'Post para Galeria' );
                    //$columns['visitas_proyectos']   = __( 'Visitas' );
                    return $columns;
                }
    
                function proyecto_column_display( $proyecto_columns, $post_id ) {
    
                    // Code from: http://wpengineer.com/display-post-thumbnail-post-page-overview
    
                    switch ( $proyecto_columns ) {
    
                        // Display the thumbnail in the column view
                        /*case 'proyecto_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;*/
    
                        // Display the category proyecto in the column view
                        case 'proyecto_category':
                            if ( $category_list     = get_the_term_list( $post_id, 'proyecto-category', '', ', ', '' ) ) {
                                /*if ( is_admin() ) {
                                    $terms          = get_the_terms( $post_id, 'proyecto-category' );
                                    foreach ( $terms as $term) {
                                        $term_padre = $term->parent;
                                    }
                                    $term_father    = get_term_by( 'id', $term_padre, 'proyecto-category' );
                                    echo qtranxf_use( 'es', $term_father->name, false ) . ' - ' . qtranxf_use( 'es', $category_list, false );
                                } else {*/
                                    echo qtranxf_use( 'es', $category_list, false );
                                /*}*/
                            } else {
                                echo __( 'None' );
                            }
                        break;
    
                        // Display the tags proyecto in the column view
                        /*case 'tag_proyectos':
                            if ( $tag_list = get_the_term_list( $post_id, 'tag_proyectos', '', ', ', '' ) ) {
                                echo qtranxf_use( 'es', $tag_list, false );
                            } else {
                                echo __( 'None' );
                            }
                        break;
    
                        // Display the id post proyecto in the column view
                        case 'galeria_proyectos':
    
                            $post_id = get_the_id();
                            if ( $post_id ) {
                                echo $post_id;
                            } else {
                                echo __( 'None' );
                            }
                        break;
    
                        // Display the visit number in the column view
                        case 'visitas_proyectos':
    
                            global $current_user;
                            get_currentuserinfo();
    
                            if ( $current_user->user_login == 'admin' ) {
                                $post_id    = get_the_id();
                                $count_key  = 'post_views_count';
                                $count      = get_post_meta( $post_id, $count_key, true );
    
                                echo $count;
                            }
                        break;*/
                    }
                }
    
                /*
                 * Adds taxonomy filters to the proyecto admin page
                 * Code artfully lifed from http://pippinsplugins.com
                 */
    
                function proyecto_add_taxonomy_filters() {
                    global $typenow;
    
                    // An array of all the taxonomyies you want to display. Use the taxonomy name or slug
                    $taxonomies = array( 'proyecto-category' );
    
                    // must set this to the post type you want the filter(s) displayed on
                    if ( $typenow == 'proyecto' ) {
    
                        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($tax_slug);
                            if ( count( $terms ) > 0) {
                                echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
                                echo "<option value=''>$tax_name</option>";
                                foreach ( $terms as $term ) {
                                    echo '<option value=' . $term->slug, $current_tax_slug == $term->slug ? ' selected="selected"' : '','>' . $term->name .' ( ' . $term->count .')</option>';
                                }
                                echo "</select>";
                            }
                        }
                    }
                }
            }
        }
        new Proyectos_post_type;
    Iniciador del debate inigonz

    (@inigonz)

    Buenas de nuevo,

    Parece que me funciona, pero me ha surgido un problema. Yo tengo en mi web diferentes post type/taxanomies: proyectos, noticias, oficinas, publicaciones,… para cada post type/taxonomy tengo un archivo de taxonomy y single, es decir, taxonomy-categoria-proyectos y single-proyecto.

    Al adaptar el código de la pagina que me has pasado ya no me reconoce la pagina de single-proyecto, si pongo single si funciona pero necesito que sea especifico para cada post type, he intenado que me diga el post type porque igual lo estoy poniendo mal, pero no me devuelve nada. Gracias

    Saludos

    Iniciador del debate inigonz

    (@inigonz)

    Buenas,

    Ya he pegado todo, y he comprobado que me funciona, ahora voy a intentar modificar mi código con este a ver que pasa

    Iniciador del debate inigonz

    (@inigonz)

    Buenas,

    Muchísimas gracias por tu ayuda y tiempo.
    Al crear los proyectos los suelo enlazar directamente a la categoría hija, en mi código detecto si la categoría es la última y dependiendo de ello me muestra una vista u otra.
    Voy a echarle un ojo al ultimo link, prisa no tengo, la web la tengo lanzada y ahora estoy haciendo una nueva versión del theme para intentar solucionar cosas que no hice bien del todo.

    saludos

    Iniciador del debate inigonz

    (@inigonz)

    ok, muchas gracias, voy echándole un vistazo, tranqui cuando tengas tiempo.
    Sip ciertamente puedo acceder directamente a la categoría hija, pero eso es muy raro, no me debería de pasar, algo tengo que tener mal en el código o eso funciona así siempre a no ser que se añada alguna función?

    • Esta respuesta fue modificada hace 7 años, 1 mes por inigonz.
    Iniciador del debate inigonz

    (@inigonz)

    He limpiado cache y esas cosas, no vaya a ser que tenga algo que ver, y a las categorías, categorias hijas,… he podido acceder, pero cuando pincho en el proyecto me lleva a la home, he visto que la url del proyecto cuando te pones encima sale bien, pero te lleva a la home, he probado a hacer todo de nuevo, pero ahora me falla cuando intento acceder a la categoría hija, alguna idea? igual hay que poner algo en el htaccess?

    Gracias

    • Esta respuesta fue modificada hace 7 años, 1 mes por inigonz.
    Iniciador del debate inigonz

    (@inigonz)

    Buenas,

    La mayúscula la había puesto para que no se pegase con el rewrite de la taxonomía, si no, no me funcionaba.
    He cambiado la mayúscula, he puesto el código que resetea las urls, cambiando lo de my_cpt_init() por mi función, he comprobado que me lo hace ya que mi menú se desactiva(menú con categorías), he eliminado el código pero me falla, entro en mi pagina, http://www.miweb.com, voy a la categoria http://www.miweb.com/cat1 sin problemas, pero cuando voy a la categoría hija me lleva a la home, intento acceder a http://www.miweb.com/cat1/hija1 pero me lleva a home, alguna idea?

    Mi estructura es, unas categorías, todas ellas tienen hijas, algunas hijas tienen hijas y los proyectos esta en las hijas finales, no se si me explico

    Gracias.

    Iniciador del debate inigonz

    (@inigonz)

    Buenas,

    Lo primero gracias por la respuesta.
    Si ciertamente me sale como tu dices pero como tengo un rewrite en los argumentos del post type, me sale http://www.miweb.com/Proyecto/categoria/proy1, pero lo que yo quiero es que me salga http://www.miweb.com/proyecto/categoria/proy1, que siga con la misma url de la taxonomy
    Ya he probado a poner en los permalinks lo de “/%category%/%postname%/” pero no me hace nada, no se si es porque es un custom post type.

    Puedo poner como he creado el post type y la taxonomy, igual ahi tengo algo mal

    Post type:

     $labels = array(
                        'name'                  => __( 'Proyectos' ),
                        'singular_name'         => __( 'Proyecto' ),
                        'add_new'               => __( 'Añadir nuevo' ),
                        'add_new_item'          => __( 'Añadir nuevo Proyecto' ),
                        'edit_item'             => __( 'Editar Proyecto' ),
                        'new_item'              => __( 'Nuevo Proyecto' ),
                        'view_item'             => __( 'Ver Proyecto' ),
                        'search_items'          => __( 'Buscar Proyecto' ),
                        'not_found'             => __( 'No se encontraron Proyectos' ),
                        'not_found_in_trash'    => __( 'No se encontraron Proyectos en la papelera' )
                    );
    
                    $args = array(
                        'labels'            => $labels,
                        'public'            => true,
                        'supports'          => array( 'title', 'editor', 'excerpt', 'thumbnail', 'page-attributes', 'post-formats' ),
                        'capability_type'   => 'post',
                        'rewrite'           => array('slug' => 'Proyectos/%categoria_proyectos%'), // Permalinks format
                        'has_archive'       => false,
                        'menu_icon'         => 'dashicons-screenoptions',
                    );
    
                    $args = apply_filters( 'proyecto_args', $args);
                    
                    register_post_type( 'proyecto', $args );

    Taxonomy:

    $taxonomy_proyecto_category_labels = array(
                        'name'                          => __( 'Categorias de Proyectos'),
                        'singular_name'                 => __( 'Categoria de Proyectos'),
                        'search_items'                  => __( 'Buscar la Categoria de Proyectos'),
                        'popular_items'                 => __( 'Categorias de Proyectos Populares'),
                        'all_items'                     => __( 'Todas las Categoria de Proyectos'),
                        'parent_item'                   => __( 'Padre de la Categoria de Proyectos'),
                        'parent_item_colon'             => __( 'Padre de la Categoria de Proyectos:'),
                        'edit_item'                     => __( 'Editar la Categoria de Proyectos' ),
                        'update_item'                   => __( 'Actualizar la Categoria de Proyectos' ),
                        'add_new_item'                  => __( 'Añadir nueva Categoria de Proyectos' ),
                        'new_item_name'                 => __( 'Nueva Categoria de Proyectos' ),
                        'separate_items_with_commas'    => __( 'Separar las Categorias de Proyectos por comas' ),
                        'add_or_remove_items'           => __( 'Añadir o Borrar Categoria de Proyectos' ),
                        'choose_from_most_used'         => __( 'Elegir entre las Categorias de Proyectos mas usadas' ),
                        'menu_name'                     => __( 'Categoria de Proyectos' ),
                    );
    
                    $taxonomy_proyecto_category_args = array(
                        'labels'            => $taxonomy_proyecto_category_labels,
                        'public'            => true,
                        'show_in_nav_menus' => true,
                        'show_ui'           => true,
                        'show_tagcloud'     => true,
                        'hierarchical'      => true,
                        'rewrite'           => array(
                            'slug'          => 'proyectos',
                            'hierarchical'  => true
                        ),
                        'query_var'         => true
                    );
    
                    $taxonomy_proyecto_category_args = apply_filters( 'taxonomy_proyecto_category_args', $taxonomy_proyecto_category_args);
                    
                    register_taxonomy( 'categoria_proyectos', array( 'proyecto' ), $taxonomy_proyecto_category_args );

    Como puedes ver en el rewrite del post type, tengo Proyectos, mientras que en la taxonomia proyecto, y no es lo mismo.

    En el post type, para poner la categoria de proyectos utilizo este filtro:

    function proyecto_post_link( $post_link, $id = 0 ) {
                $post = get_post($id);
    
                if ( is_object( $post ) ) {
                    if ( $post->post_type == 'proyecto' ) {
                        $terms = wp_get_object_terms( $post->ID, 'categoria_proyectos' );
                        if ( $terms ) {
                            $parent     = $terms[0]->parent;
                            $url        = $terms[0]->slug;
                            while ( $parent != 0 ) {
                                $terms  = get_term_by( 'parent', $parent, 'categoria_proyectos' );
                                $url    = $terms->slug . '/' . $url;
                                $parent = $terms->parent;
                            }
    
                            return str_replace( '%categoria_proyectos%' , $url , $post_link );
                        }
                    }
                }
                return $post_link;
            }
            add_filter( 'post_type_link', 'proyecto_post_link', 1, 3 );

    Gracias

    • Esta respuesta fue modificada hace 7 años, 1 mes por inigonz.
Viendo 15 respuestas - de la 31 a la 45 (de un total de 55)