WordPress Custom Post Type Permalinks ohne Pfad

Permalinks für Custom Post Types in WordPress ohne Pfad erzwingen

Wenn die globale Einstellung der Permalinks z.B. auf blog/%postname% steht, werden die Custom Post Types Single Seiten mit Elternpfad angezeigt. Um dabei URLs mit %postname% (also ohne Pfad) auszugeben, ist das seit WP Version 4 etwas tricky. Hier ein Lösungsansatz:

 

function init_my_custom_post()
{
	global $wp_rewrite;

	$args = array(
	    ...
	    'query_var' => true,
	    'rewrite' => array('slug' => 'my-post-type-slug', 'with_front' => false),
	    'capability_type' => 'post',
	    'has_archive' => true,
	    'hierarchical' => false,
	    ...
	);

	//register your cotum post type
	register_post_type('my_custom_post_type', $args);

	//register the rewrite tag for permalink building
    $wp_rewrite->add_rewrite_tag( '%customname%', '([^/]+)', 'name=my_custom_post_type#' );

    //we have to add the permastruct here in order to build the permalink, otherwise we'll need to filter the post_type link
    add_permastruct('my_custom_post_type', '%customname%/', false );

	// add a filter to remove the permastructs generated above
    add_filter('my_custom_post_type'.'_rewrite_rules', 'my_custom_post_type_remove_default_rules'); 

    // add a filter to put the generated rewrite rules
    add_filter('rewrite_rules_array', 'my_custom_post_type_filter_rewrite_rules');

    // add a filter to remove the path from permalink
    add_filter('post_type_link', 'my_custom_post_type_permalinks');

    // manipulate the given query
    add_action( 'pre_get_posts', 'my_custom_post_type_query' );
}

add_action( 'init', 'init_my_custom_post' );


function my_custom_post_type_remove_default_rules($rules)
{
    return array();
}

function my_custom_post_type_filter_rewrite_rules($rewrite_rules_array) 
{
	global $wp_rewrite;
	return array_merge($rewrite_rules_array, $wp_rewrite->generate_rewrite_rules("/%customname%/", EP_NONE));
}
function my_custom_post_type_permalinks( $permalink, $post ) {
    return str_replace( '%customname%/', $post->post_name, $permalink );
}
function my_custom_post_type_query($query)
{
	 if ( ! $query->is_main_query() ) {
	 	return;
	 }

	 if( isset($query['name']) && preg_match('/^my_custom_post_type#/', $query['name']) ){

	 	global $wpdb;
	 	$post_name = str_replace('my_custom_post_type#', '', $query['name']);

	 	$result = $wpdb->get_row('SELECT ID FROM '.$wpdb->get_prefix.'posts WHERE post_name = \''. $post_name . '\' AND post_status= '\publish'\ AND post_type = \'my_custom_post_type\', 'ARRAY_IN');

	 	if(!empty($result)){
	 		$query->set('post_type', array('post', 'my_custom_post_type', 'page' ));
	 		$query->set('my_custom_post_type', $post_name);
	 	}


	 }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.