Tipos de correos personalizados, taxonomías y enlaces permanentes

60

Esto me está volviendo loco y estoy seguro de que es simple, pero nada de lo que busco es una estructura simple (todo es muy complejo).

Tengo un tipo de publicación personalizado product_listing y una taxonomía personalizada de product_cat (que es jerárquica y debería tener categorías similares).

Simplemente quiero que mis URL se vean así:

mysite.com/products/category1/product-name1 
mysite.com/products/category2/product-name2

Pero por mi vida, no importa lo que haga, estoy recibiendo el temido problema 404. Las páginas funcionan bien y las publicaciones funcionan bien, pero mis publicaciones personalizadas no funcionan correctamente. Se muestran como:

mysite.com/products/product-name1
mysite.com/products/product-name2

Lo que realmente funciona ! Es solo que quiero ver mi taxonomía personalizada y quiero poder acceder a la plantilla taxonomy.php que he configurado yendo a:

mysite.com/products/category1/
mysite.com/products/category2/

Ninguna de mis babosas es igual, ni quiero que sean. Aquí está el tipo de publicación y la parte de taxonomía de mi archivo functions.php :

///// CUSTOM POST TYPES /////

// register the new post type
register_post_type( 'product_listing', array( 
    'labels'                 => array(
        'name'               => __( 'Products' ),
        'singular_name'      => __( 'Product' ),
        'add_new'            => __( 'Add New' ),
        'add_new_item'       => __( 'Create New Product' ),
        'edit'               => __( 'Edit' ),
        'edit_item'          => __( 'Edit Product' ),
        'new_item'           => __( 'New Product' ),
        'view'               => __( 'View Products' ),
        'view_item'          => __( 'View Product' ),
        'search_items'       => __( 'Search Products' ),
        'not_found'          => __( 'No products found' ),
        'not_found_in_trash' => __( 'No products found in trash' ),
        'parent'             => __( 'Parent Product' ),
    ),
    'description'           => __( 'This is where you can create new products on your site.' ),
    'public'                => true,
    'show_ui'               => true,
    'capability_type'       => 'post',
    'publicly_queryable'    => true,
    'exclude_from_search'   => false,
    'menu_position'         => 2,
    'menu_icon'             => get_stylesheet_directory_uri() . '/images/tag_orange.png',
    'hierarchical'          => true,
    '_builtin'              => false, // It's a custom post type, not built in!
    'rewrite'               => array( 'slug' => 'products', 'with_front' => true ),
    'query_var'             => true,
    'supports'              => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions' ),
) );


//hook into the init action and call create_book_taxonomies when it fires
add_action( 'init', 'create_product_taxonomies', 0 );
//add_action('admin_init', 'flush_rewrite_rules');

//create two taxonomies, genres and writers for the post type "book"
function create_product_taxonomies() {
    // Add new taxonomy, make it hierarchical (like categories)
    $labels = array(
        'name'              => _x( 'Categories', 'taxonomy general name' ),
        'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
        'search_items'      =>  __( 'Search Categories' ),
        'all_items'         => __( 'All Categories' ),
        'parent_item'       => __( 'Parent Categories' ),
        'parent_item_colon' => __( 'Parent Categories:' ),
        'edit_item'         => __( 'Edit Category' ), 
        'update_item'       => __( 'Update Category' ),
        'add_new_item'      => __( 'Add New Category' ),
        'new_item_name'     => __( 'New Category Name' ),
        'menu_name'         => __( 'Category' ),
    );  

    register_taxonomy( 'product_cat', array( 'product_listing' ), array(
        'hierarchical'  => true,
        'labels'        => $labels,
        'show_ui'       => true,
        'query_var'     => true,
        //'rewrite'     => true,
        'rewrite'       => array( 'slug' => '%category%', 'with_front' => true ),
    ) );

    // Add new taxonomy, NOT hierarchical (like tags)
    $labels = array(
        'name'                       => _x( 'Scents', 'taxonomy general name' ),
        'singular_name'              => _x( 'Scent', 'taxonomy singular name' ),
        'search_items'               =>  __( 'Search Scents' ),
        'popular_items'              => __( 'Popular Scents' ),
        'all_items'                  => __( 'All Scents' ),
        'parent_item'                => null,
        'parent_item_colon'          => null,
        'edit_item'                  => __( 'Edit Scent' ), 
        'update_item'                => __( 'Update Scent' ),
        'add_new_item'               => __( 'Add New Scent' ),
        'new_item_name'              => __( 'New Scent Name' ),
        'separate_items_with_commas' => __( 'Separate scents with commas' ),
        'add_or_remove_items'        => __( 'Add or remove scents' ),
        'choose_from_most_used'      => __( 'Choose from the most used scents' ),
        'menu_name'                  => __( 'Scents' ),
    ); 

    register_taxonomy( 'scent', 'product_listing', array(
        'hierarchical'  => false,
        'labels'        => $labels,
        'show_ui'       => true,
        'query_var'     => true,
        //'rewrite'     => array( 'slug' => 'scents' ),
    ) );
}

También tengo otra taxonomía personalizada de scents que idealmente me gustaría tener algún tipo de URL amigable pero estoy más abierto a esto. Me gustaría tal vez acceder a una lista de todos los aromas yendo a mysite.com/products/scents , pero no tienen que ser específicos de la categoría.

¿Puede alguien ayudarme?

    
pregunta RodeoRamsey 14.12.2010 - 00:56

5 respuestas

62

Cambie slug en sus argumentos de tipo de publicación a products/%product_cat% , y slug en sus argumentos de taxonomía a solo products , luego borre sus reglas de reescritura. WordPress ahora debe manejar /products/my-product-cat/post-name/ !

Finalmente, necesitamos ayudar a WordPress un poco con la generación de enlaces permanentes (fuera de la caja, no reconocerá la etiqueta permastruct %product_cat% ):

/**
 * Inject term slug into custom post type permastruct.
 * 
 * @link   http://wordpress.stackexchange.com/a/5313/1685
 * 
 * @param  string  $link
 * @param  WP_Post $post 
 * @return array
 */
function wpse_5308_post_type_link( $link, $post ) {
    if ( $post->post_type === 'product_listing' ) {
        if ( $terms = get_the_terms( $post->ID, 'product_cat' ) )
            $link = str_replace( '%product_cat%', current( $terms )->slug, $link );
    }

    return $link;
}

add_filter( 'post_type_link', 'wpse_5308_post_type_link', 10, 2 );

Una cosa a tener en cuenta, esto solo tomará la primera categoría de producto para la publicación ordenada por nombre . Si está asignando múltiples categorías a un solo producto, puedo cambiar fácilmente la forma en que determina cuál usar en el enlace permanente.

Déjame saber cómo te va con esto, ¡y podemos abordar los otros problemas!

    
respondido por el TheDeadMedic 14.12.2010 - 02:50
6

Gracias, @TheDeadMechanic, su respuesta me ayudó, pero solo parcialmente. Quería hacer lo mismo que pidió @RodeoRamsey, pero con categorías anidadas (es decir, mysite.com/products/category1/child-category-1/grandchild-category-1/product-name ) y su solución no funcionó para eso.

Finalmente encontré una solución extendida a mi pregunta que funciona, así que si alguien más necesita categorías / subcategorías anidadas, puede ver un solución detallada en mi propia pregunta. Espero que ayude a otros, y gracias por los pasos iniciales.

    
respondido por el Jeff 23.01.2012 - 19:39
4

No estoy seguro de que wp admita esa estructura fuera de la caja, pero puedes crear fácilmente tus propias reglas de reescritura para hacerlo.

Verifique una respuesta anterior aquí Reescritura de la URL del autor .

Puedes cambiar la línea

$newrules['author/([^/]+)/songs/?$'] = 'index.php?post_type=songs&author=$matches[1]';

a algo como

$newrules['products/([^/]+)/([^/]+)/?$'] = 'index.php?post_type=product_listing&product_cat=$matches[1]&name=$matches[2]';

la parte product_cat aquí puede ser superflua, no estoy seguro de que sea necesario.

Puedes agregar cualquier regla que desees y tendrán prioridad sobre las incorporadas.

    
respondido por el Chris 14.12.2010 - 01:07
2

Sí, me estaba volviendo loco antes de establecer el enlace permanente para el tipo de publicación personalizada. Encontré un plugin para manejar el tipo de mensaje personalizado. Es muy fácil de usar. enlace WP debería agregar esto como una característica principal! Leo

    
respondido por el user1975 14.12.2010 - 11:13
0

En realidad, es bastante fácil. Sólo necesitas una línea. Aquí está mi código

function create_product_taxonomies()
{
// Add new taxonomy, make it hierarchical (like categories)
    $labels = array(
        'name' => _x('Categories', 'taxonomy general name'),
        'singular_name' => _x('Category', 'taxonomy singular name'),
        'search_items' => __('Search Categories'),
        'all_items' => __('All Categories'),
        'parent_item' => __('Parent Categories'),
        'parent_item_colon' => __('Parent Categories:'),
        'edit_item' => __('Edit Category'),
        'update_item' => __('Update Category'),
        'add_new_item' => __('Add New Category'),
        'new_item_name' => __('New Category Name'),
        'menu_name' => __('Category'),
    );

    register_taxonomy('product_cat', array('product_listing'), array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array('hierarchical' => true),
    ));

Y se aplica a la taxonomía generada para mis comentarios CPT de GenerateWP.com. Estoy usando esto en mi propio sitio de WordPress, enlace

function reviews_category_taxonomy() {

    $labels = array(
        'name'                       => _x( 'Reviews Categories', 'Taxonomy General Name', 'reviews_category' ),
        'singular_name'              => _x( 'Reviews Category', 'Taxonomy Singular Name', 'reviews_category' ),
        'menu_name'                  => __( 'Reviews Category', 'reviews_category' ),
        'all_items'                  => __( 'All Review Categories', 'reviews_category' ),
        'parent_item'                => __( 'Parent Review Category', 'reviews_category' ),
        'parent_item_colon'          => __( 'Parent Review Category:', 'reviews_category' ),
        'new_item_name'              => __( 'New Review Category Name', 'reviews_category' ),
        'add_new_item'               => __( 'Add New Review Category', 'reviews_category' ),
        'edit_item'                  => __( 'Edit Review Category', 'reviews_category' ),
        'update_item'                => __( 'Update Review Category', 'reviews_category' ),
        'view_item'                  => __( 'View Review Category', 'reviews_category' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'reviews_category' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'reviews_category' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'reviews_category' ),
        'popular_items'              => __( 'Popular Review Categories', 'reviews_category' ),
        'search_items'               => __( 'Search Items', 'reviews_category' ),
        'not_found'                  => __( 'Not Found', 'reviews_category' ),
        'no_terms'                   => __( 'No Review Categories', 'reviews_category' ),
        'items_list'                 => __( 'Review Categories list', 'reviews_category' ),
        'items_list_navigation'      => __( 'Review Categories list navigation', 'reviews_category' ),
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => false,
        'show_in_rest'               => true,
        'rewrite' => array( 'hierarchical' => true ),
    );
    register_taxonomy( 'reviews_category', array( 'wps_reviews' ), $args );

}
add_action( 'init', 'reviews_category_taxonomy', 0 );

Todo lo que necesita, así que ponga 'reescribir' = > array ('jerárquico' = > verdadero),

    
respondido por el Leo Koo 06.12.2017 - 20:15

Lea otras preguntas en las etiquetas