custom-post-types – Enlace permanente de tipo de publicación personalizada: solo use% post_id% y elimine% postname%

Pregunta:

He creado un tipo de publicación personalizada en WordPress que está funcionando muy bien. Lo único que necesito resolver son los enlaces permanentes creados por este CTP.

Actualmente tengo:

example.com/<custom-post-name>/<post-id>/<postname>/

Quiero que solo muestre el post-id:

example.com/<custom-post-name>/<post-id>/

El tipo de publicación personalizada está registrado con:

function create_post_type_mycustomname() {
    $args = array(
        'capability_type' => 'post',
        'has_archive' => 'mycustomname',
        'rewrite' => array(
            'slug' => '/mycustomname/%post_id%',
            'feeds' => false
        )
    );

    register_post_type('ctp_mycustomname', $args);
}
add_action('init', 'create_post_type_mycustomname');

Y el %post_id en el slug se reemplaza con lo siguiente:

function custom_post_mycustomname_link($post_link, $post = 0, $leavename = false) {
    if($post->post_type == 'ctp_mycustomname') {
        return str_replace('%post_id%', $post->ID, $post_link);
    }
    else {
        return $post_link;
    }
}
add_filter('post_type_link', 'custom_post_mycustomname_link', 1, 3);

¿Alguna sugerencia sobre cómo quitar el nombre de la publicación de este tipo de URL?

Respuesta:

Encontré la respuesta yo mismo, así que aquí está la actualización del problema anterior:

Registro de tipo de publicación personalizada:

function create_post_type_mycustomname() {
    $args = array(
        'capability_type' => 'post',
        'has_archive' => 'mycustomname',
        'rewrite' => array(
            'slug' => '/mycustomname',
            'feeds' => false
        )
    );

    register_post_type('ctp_mycustomname', $args);
}
add_action('init', 'create_post_type_mycustomname');

Cambiar los enlaces:

function mycustomname_links($post_link, $post = 0) {
    if($post->post_type === 'ctp_mycustomname') {
        return home_url('mycustomname/' . $post->ID . '/');
    }
    else{
        return $post_link;
    }
}
add_filter('post_type_link', 'mycustomname_links', 1, 3);

Agregue las reglas de reescritura correctas:

function mycustomname_rewrites_init(){
    add_rewrite_rule('mycustomname/([0-9]+)?$', 'index.php?post_type=ctp_mycustomname&p=$matches[1]', 'top');
}
add_action('init', 'mycustomname_rewrites_init');

Elimine las reglas de reescritura en el backend de WordPress y listo.

Leave a Comment

Your email address will not be published. Required fields are marked *

web tasarım