0

hi like state on the title , how can i achieve this ? i've try lots of plugins and its all only work with custom post types only.

so here is the situation , i have a custom post types (food) , and for the recipes i use wordpress posts ,

and i want to make the post permalinks become /recipes/my-awesome-title for old and new post. i know i can change this in permalink section but if i add /recipes/%postname/ ,

my custom post also become /recipes/food/my-awesome-title and that is not what i want.

i dont try any code yet except install couple of plugins since i can do codes in wp and depends on plugins instead.

according to this a link i have to register post type which i have no idea at all how to do that , please help me for those who capable of , thank you before for your kindness.

edited: i found this snippets

function filter_post_link($permalink, $post) {
    if ($post->post_type != 'post')
        return $permalink;
    return 'recipes'.$permalink;
}
add_filter('pre_post_link', 'filter_post_link', 10, 2);

my post becomes /recipes/my-awesome-post but i got redirect loop redirected you too many times.

any idea why ? i have also update my permalink

3
  • How do you register the food cpt? Did you set the with_front argument? – Milo Apr 15 '18 at 14:52
  • hi , dont need to register anything . just use the code on my answered below – DRMTV Apr 15 '18 at 20:36
  • The code in your answer is not necessary if you register the food custom post type with the correct arguments. – Milo Apr 15 '18 at 21:05
1

ok so after searching again i found this and it worked

/**
 * Add new rewrite rule
 */
function create_new_url_querystring() {
    add_rewrite_rule(
        'recipes/([^/]*)$',
        'index.php?name=$matches[1]',
        'top'
    );
    add_rewrite_tag('%recipes%','([^/]*)');
}
add_action('init', 'create_new_url_querystring', 999 );
/**
 * Modify post link
 * This will print /recipes/post-name instead of /post-name
 */
function append_query_string( $url, $post, $leavename ) {
    if ( $post->post_type == 'post' ) {     
        $url = home_url( user_trailingslashit( "recipes/$post->post_name" ) );
    }
    return $url;
}
add_filter( 'post_link', 'append_query_string', 10, 3 );
/**
 * Redirect all posts to new url
 * If you get error 'Too many redirects' or 'Redirect loop', then delete everything below
 */
function redirect_old_urls() {
    if ( is_singular('post') ) {
        global $post;
        if ( strpos( $_SERVER['REQUEST_URI'], '/recipes/') === false) {
           wp_redirect( home_url( user_trailingslashit( "recipes/$post->post_name" ) ), 301 );
           exit();
        }
    }
}
add_filter( 'template_redirect', 'redirect_old_urls' );

link to the full post can be found a link here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.