How to Change URL Prefix For Custom Post Types in WordPress

While developing our own website with WordPress I came across one issue with URL structure of blog and portfolio pages. I needed to have blog post URL to be axiswebart.com/blog/posturl. To achieve this I used WordPress permalinks settings and added a URL prefix using custom permalinks options as blog/%postname%/

This solved one problem with blog URL and created another one. Now all our portfolio pages also started to have this URL prefix and all url portfolio URL started to have two url prefix with a structure like axiswebart.com/blog/portfolio/portfolioitmeurl

We don’t wanted to have this kind of structure at all. After searching around the internet I came across below solution to fix the problem –

We have registered a custom post type for our portfolio and I added below line of code in the post type register function of the plugin.

'rewrite' => array(
'with_front' => false,
'slug'       => 'portfolio'
)

Hope this helps anyone looking for a solution to problem like this with custom post type. Even if your URL don’t work after adding this code, make sure you refresh your rewrite rules stored in the wp_options table. To refresh that try saving your permalinks settings to default once and than reset it back to your original settings. It will regenerate all rewrite rule and your custom post type URL will start working as per your settings.

Show Different Posts Per Page/category in WordPress Website

Many times you need to show different number of post per category page in WordPress. Use below code snippet do that.

Code For Show Different Posts Per Page.

Add this code in function.php of your theme

function five_posts_on_homepage( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 5 );
    }
}
add_action( 'pre_get_posts', 'five_posts_on_homepage' );

Categories