justsomeone
justsomeone

Reputation: 37

Replace custom content type slug in Wordpress

In WordPress, I'm using Jetpack's portfolio custom content type, but would like to change the slug from "portfolio" to "examples". I found this example on how to do it (http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/) and this plugin (https://github.com/devinsays/no-slug-portfolio-post-types). Both as based on a post on Wordpress VIP that was linked to by the Jetpack team and now has a dead link.

Here is my code, for some reason it is not working. I have refreshed my permalinks by going to Settings > Permalinks and hitting save changes.

/**
 * Remove the slug from custom post type permalinks.
 */
function vipx_remove_cpt_slug( $post_link, $post, $leavename ) {

    if ( ! in_array( $post->post_type, array( 'portfolio' ) ) || 'publish' != $post->post_status )
        return $post_link;

    $post_link = str_replace( '/' . $post->post_type . '/', '/examples', $post_link );

    return $post_link;
}
add_filter( 'post_type_link', 'vipx_remove_cpt_slug', 10, 3 );

/**
 * Some hackery to have WordPress match postname to any of our public post types
 * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
 * Typically core only accounts for posts and pages where the slug is /post-name/
 */
function vipx_parse_request_tricksy( $query ) {

    // Only noop the main query
    if ( ! $query->is_main_query() )
        return;

    // Only noop our very specific rewrite rule match
    if ( 2 != count( $query->query )
        || ! isset( $query->query['page'] ) )
        return;

    // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
    if ( ! empty( $query->query['name'] ) )
        $query->set( 'post_type', array( 'post', 'portfolio', 'page' ) );
}
add_action( 'pre_get_posts', 'vipx_parse_request_tricksy' );

Any ideas how to get this code working again?

Upvotes: 2

Views: 834

Answers (1)

Nikunj Kathrotiya
Nikunj Kathrotiya

Reputation: 963

function na_remove_slug($post_link, $post, $leavename) {
    if ('POST TYPE SLUG' != $post - > post_type || 'publish' != $post - > post_status) {
        return $post_link;
    }
    $post_link = str_replace('/'.$post - > post_type.
        '/', '/', $post_link);
    return $post_link;
}
add_filter('post_type_link', 'na_remove_slug', 10, 3);
function na_parse_request($query) {
    if (!$query - > is_main_query() || 2 != count($query - > query) || !isset($query - > query['page'])) {
        return;
    }
    if (!empty($query - > query['name'])) {
        $query - > set('post_type', array('post', 'POST TYPE SLUG', 'page'));
    }
}
add_action('pre_get_posts', 'na_parse_request');

Upvotes: 1

Related Questions