February 8, 2019

Lesson 03: URLs in Custom Post Types

Here is a quick and easy step-by-step tutorial on how to customize the URL structure of a Custom Post Type in WordPress. You will need a basic knowledge of PHP coding and WordPress functions.

Step 1: Create a Custom Post Type

In order to create a Custom Post Type, check out https://codex.wordpress.org/custom_post_types where you will all needed arguments and codes. Keep in mind that in order to add custom fields to your URL, you should use:

‘query_var’ => true,
function mad_register_custom_post_type() {
$args = array(
‘labels’ => array(
‘name’ => __( ‘Business Directory’ ),
‘singular_name’ => __( ‘Business Directory’ )
),
‘menu_position’ => 5,
‘public’ => true,
‘has_archive’ => ‘true’,
‘hierarchical’ => true,
‘query_var’ => true,
‘rewrite’ => false,
‘capability_type’ => ‘post’,
‘supports’ => array(‘title’, ‘editor’, ‘thumbnail’, ‘revisions’, ‘page-attributes’)
);
register_post_type(‘business-directory’, $args);
}
add_action( ‘init’, ‘mad_register_custom_post_type’ );

Step 2: Create Rewrite Rules

add_action(‘init’, ‘mad_add_rewrite_rules’);
function mad_add_rewrite_rules() {
// Register custom rewrite rules
add_rewrite_tag(‘%business-directory%’, ‘([^/]+)’); //Name of the posttype
add_rewrite_tag(‘%custom_field_name%’, ‘([^/]+)’);//Name of the custom field
add_permastruct(‘business-directory’, ‘business-directory/%custom_field_name%/%business-directory%’, false);
}

Step 3: Add a Custom Field to the URL

add_action(‘init’, ‘madRewriteRules’);
function madRewriteRules() {
//Register custom rewrite rules
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag(‘%custom_field_name%’, ‘([^/]+)’, ‘custom_field_name=’);
$wp_rewrite->add_permastruct(‘custom_field_name’, ‘/business-directory/%custom_field_name%’, false);
}

Step 4: Find the Custom Post Type and Your Desired Permalink

add_filter(‘post_type_link’, ‘maadPermalinks’, 10, 3);
function maadPermalinks($permalink, $post, $leavename) {
$no_data = ‘no-field’;
$post_id = $post->ID;
if($post->post_type != ‘custom_field_name’ || empty($permalink) || in_array($post->post_status, array(‘draft’, ‘pending’, ‘auto-draft’)))
return $permalink;
$var1 = $post->post_name;
$var1 = sanitize_title($var1);
if(!$var1) { $var1 = $no_data; }
$permalink = str_replace(‘%custom_field_name%’, $var1, $permalink);
return $permalink;
}