inigonz
Respuestas de foro creadas
-
Foro: WordPress Avanzado
En respuesta a: Permisos para editar posts de otro autorBuenas,
Ciertamente veo que cojeo en la forma de programar en wp, todas las funciones las pongo en el functions, o las añado a otro archivo php para dejarlo todo mas limpio.
Lo único que si controlo algo más, es la creación de mis post types, que los creo de esta manera:
if ( !class_exists( 'postTypes' ) ) { class postTypes { function __construct() { add_action( 'init', array( &$this, 'postTypes_init' ), 0 ); add_filter( 'manage_edit-proyecto_columns', array( &$this, 'pr_edit_columns' ) ); add_action( 'manage_posts_custom_column', array( &$this, 'postTypes_column_display' ), 10, 2 ); add_action( 'restrict_manage_posts', array( &$this, 'add_me_tax_filters' ) ); } function postTypes_init() { creacion.... } function pr_edit_columns( $columns ) { columnas } function postTypes_column_display( $columns, $post_id ) { contenido columnas } function add_me_tax_filters() { filtro de las taxonomia } } } new postTypes;
Los plugins de terceros, tienen su lado bueno y su lado malo. Como pilles uno que se deje de actualizar como ya me ha pasado con alguno, te lo comes pero bien, sobretodo cuando empieza a dar errores y es un plugin que no puedes eliminar porque es importante en tu web.
Bueno si no consigo lo de los permisos, lo desactivo que tampoco pasa nada, era por tener todo mas atado.
Saludos
- Esta respuesta fue modificada hace 6 años, 3 meses por inigonz.
Foro: WordPress Avanzado
En respuesta a: Permisos para editar posts de otro autorMuchísimas gracias por tu ayuda.
Lo que propones de crearlo como post type, ahora mismo no lo veo, pero no es mala opción.
Utilizar plugins de terceros, siempre es una opción pero estoy intentando usar el mínimo número de plugins posibles, para tenerlo todo más controlado.
Pero lo que comentas de que antes de guardar comprueba la capacidad … me has dado un idea, a ver si consigo hacerlo, si lo consigo ya pongo el código aquí.Un saludo y muchas gracias
Foro: WordPress Avanzado
En respuesta a: Permisos para editar posts de otro autorOK, muchas gracias por la respuesta.
A mi el código que he puesto lo pego en mi functions.phpp y me funciona perfectamente, hay una variable ($cpt_pr) que me ha quedado colgando, pero si se sustituye por proyecto funciona.
Asignar el rol reca a los usuarios, no lo hago por código, lo hago desde el admin, al crear el usuario.
Todo esto que quiero conseguir es porque tengo en mi web, diferentes usuarios y no quiero que por error puedan editar los proyectos de los otros usuarios, a no ser que pertenezcan a la misma categoría.
Saludos
Foro: WordPress Avanzado
En respuesta a: Permisos para editar posts de otro autorBuenas,
Si, a ver como queda:
// CPT PROYECTO $pr_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' ) ); $pr_args = array( 'labels' => $pr_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', 'author' ), 'capability_type' => 'proyecto', 'capabilities' => array( 'edit_post' => 'edit_proyecto', 'read_post' => 'read_proyecto', 'delete_post' => 'delete_proyecto', 'edit_posts' => 'edit_proyectos', 'edit_others_posts' => 'edit_others_proyectos', 'publish_posts' => 'publish_proyectos', 'read_private_posts' => 'read_private_proyectos', 'create_posts' => 'edit_proyectos', 'delete_posts' => 'delete_proyectos', 'delete_others_posts' => 'delete_others_proyectos', ), //'map_meta_cap' => true, 'hierarchical' => false, 'has_archive' => true, 'rewrite' => array( 'slug' => $cpt_pr, /*'hierarchical' => true, 'with_front' => false*/ ), 'menu_icon' => 'dashicons-screenoptions' ); $pr_args = apply_filters( 'proyecto_args', $pr_args ); register_post_type( 'proyecto', $pr_args );
// Crear Rol para los Recas $caps = array( 'read' => true, 'upload_files' => true, 'edit_theme_options' => true, 'gmedia_library' => true, 'gmedia_upload' => true, 'gmedia_import' => true, 'gmedia_edit_media' => true, 'gmedia_delete_media' => true, 'gmedia_album_manage' => true, 'gmedia_tag_manage' => true, ); add_role( 'reca', 'Reca', $caps ); function add_theme_caps_postTypes() { $role = get_role( 'reca' ); $cpts = array( 'proyectos' ); foreach ( $cpts as $cpt ) { $role->add_cap( 'edit_' . $cpt ); //$role->add_cap( 'edit_others_' . $cpt ); $role->add_cap( 'publish_' . $cpt ); $role->add_cap( 'delete_' . $cpt ); } } add_action( 'admin_init', 'add_theme_caps_postTypes');
// Funcion que da permisos para leer/escribir/eliminar a los proyectos add_filter( 'map_meta_cap', 'postTypes_meta_cap', 10, 4 ); function postTypes_meta_cap( $caps, $cap, $user_id, $args ) { // Si es una capacidad meta tipo "proyecto", obtener el post y el objeto del post type que se utilizará más adelante if ( 'edit_proyecto' == $cap || 'delete_proyecto' == $cap || 'read_proyecto' == $cap ) { $post = get_post( $args[0] ); $post_type = get_post_type_object( $post->post_type ); $caps = array(); // vaciar $caps $permisos = of_get_option( $user_id . 'permisos' ); $term = get_the_terms( $post, 'mercado' ); } // Si se va a editar un "proyecto", asignar las capacidades correspondientes if ( 'edit_proyecto' == $cap ) { if ( $user_id == $post->post_author || $permisos[$term[0]->term_id] == 1 ) { // Si el usuario es el autor del post, comprobar si el usuario tiene la capaciad edit_posts $caps[] = $post_type->cap->edit_posts; } else { // Si el usuario no es el autor del post, comprobar si el usuario tiene la capacidad edit_others_posts $caps[] = $post_type->cap->edit_others_posts; } } // Si se va a borrar un proyecto if ( 'delete_proyecto' == $cap ) { if ( $user_id == $post->post_author || $permisos[$term[0]->term_id] == 1 ) { $caps[] = $post_type->cap->delete_posts; } else { $caps[] = $post_type->cap->delete_others_posts; } } // Si se va a leer un proyecto privado if ( 'read_proyecto' == $cap ) { if ( 'private' != $post->post_status ) { $caps[] = 'read'; } elseif ( $user_id == $post->post_author || $permisos[$term[0]->term_id] == 1 ) { $caps[] = 'read'; } else { $caps[] = $post_type->cap->read_private_posts; } } // Devolver las capacidades que debe tener el usuario return $caps; }
Lo de los permisos, es con el options framework
Si necesitais alguna cosa mas me decis, gracias.
Foro: Multisitio
En respuesta a: Problema con las urls: WP Multisite con custom post typeCreo que lo he solucionado.
En el custom post type, en el rewrite/url he puesto noticia o new dependiendo del idioma.
Y luego he modificado un poco la funcion de arriba, añadiendo lo contrario, es decir,
function my_msls_options_get_permalink( $url, $language ) { if ( 'en_GB' == $language ) { $url = str_replace( '/noticia/', '/new/', $url ); } else { $url = str_replace( '/new/', '/noticia/', $url ); } return $url; } add_filter( 'msls_options_get_permalink', 'my_msls_options_get_permalink', 10, 2 );
No se si será la forma correcta, por ahora no me ha explotado nada
Saludos
Foro: Multisitio
En respuesta a: Problema con las urls: WP Multisite con custom post typeY alguna solución con código para solucionar la traducción de post types? prefiero controlar yo las urls, con los rewrites.
Gracias
Foro: Multisitio
En respuesta a: Problema con las urls: WP Multisite con custom post typeBuenas,
Gracias por la respuesta.
He tenido malas experiencias con plugins de idiomas, así que he decidido pasarme a wp-multisite con el plugin Multisite Language Switcher que me soluciona lo de los idiomas, pero no me permite traducir los post typesForo: WordPress Avanzado
En respuesta a: Varios Post Type con la misma taxonomiaMuchas 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
Foro: WordPress Avanzado
En respuesta a: Varios Post Type con la misma taxonomiaBuenas 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
Foro: WordPress Avanzado
En respuesta a: Varios Post Type con la misma taxonomiaEn 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
Foro: WordPress Avanzado
En respuesta a: Varios Post Type con la misma taxonomiaBuenas 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 ) . '¬icia=' . $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 ) . '¬icia=' . $wp_rewrite->preg_index( 3 ), PostType_lang_rewrite('noticia') . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=noticia&departamento=' . $wp_rewrite->preg_index( 3 ) . '¬icia=' . $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
Foro: WordPress Avanzado
En respuesta a: Varios Post Type con la misma taxonomiaGracias 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
Foro: WordPress Avanzado
En respuesta a: Mostrar custom post type con custom taxonomy termBuenas,
Yo tengo algo parecido a lo tuyo, pero sin utilizar el nombre de la taxonomía en la url, es decir, yo tengo http://www.prueba.com/posttype/term/termhijo/ pero entiendo que solo tendrías que añadir a la url a mano tu taxonomía.
Utilizo reglas para redireccionar:
// 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 ) . '¬icia=' . $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 ) . '¬icia=' . $wp_rewrite->preg_index( 3 ), PostType_lang_rewrite('noticia') . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=noticia&departamento=' . $wp_rewrite->preg_index( 3 ) . '¬icia=' . $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 );
La funcion PostType_lang_rewrite() la utilizo para traducir proyecto/project y noticia/new porque es un multisite, pero tu no tendrías que utilizar.
El único pequeño problema que tengo, es que aunque la url tenga prueba.com/proyecto/categoria1/categoria1.1 me dice que el post type es noticia, ya que no sabe con que post type lo coge, y para solucionarlo he echo un pequeño parche, compruebo en la url si tiene noticia o proyecto.
No se si con eso te he dado alguna luzSaludos
Foro: WordPress Avanzado
En respuesta a: Custom Taxonomy/Post Type URLBuenas,
Al final he vuelto a seguir lo de los templates que me comentabas antes, porque con el código del link anterior no consigo na de na. He buscado un poco por internet y con este código funciona perfectamente,
add_action( 'template_redirect', 'my_fancy_template_redirect' ); function my_fancy_template_redirect(){ global $wp_query; /* Check if we are querying proyecto-posts: */ if ( $wp_query->query_vars['post_type'] == 'proyecto' ) { /* Then check if we are dealing with a single proyecto post or just multiple proyecto posts: */ if ( is_single() ) { locate_template( array( 'templates/proyecto-single.php', 'single.php', 'index.php' ), true ); die(); } } }
Foro: WordPress Avanzado
En respuesta a: Custom Taxonomy/Post Type URLBuenas,
Tranquilo, no pasa na.
Justo ayer vi una solución parecida a esta pero no me convenció mucho esto de utilizar templates, no me cogía los css o algo raro me pasaba.
He encontrado una solución pero no esta del todo acabada, http://www.ibenic.com/custom-wordpress-rewrite-rule-combine-taxonomy-post-type/. Faltaría poner toda la ruta de categorías padre ya que solo pone la última, todo lo demás funciona bien, a ver si consigo maquearlo para que funcione a mi gustoGracias