サポート » 使い方全般 » カスタム投稿タイプとカスタム分類のパーマリンクで404に

  • 解決済 kazaisyu

    (@kazaisyu)


    URLを
    /カスタム投稿/カスタム分類/投稿名(スラッグ) から
    /カスタム分類/投稿名(スラッグ) に変更したく、カスタム投稿名を抜けないか試行錯誤しています。
    しかし、パーマリンクは変更できるものの、該当のページで404が発生してしまいます…。色々と弄ってはみたもののうまくいかない状態です。
    どうか何卒、お力をお貸しいただければ幸いです。

    add_action( 'init', 'create_post_type' );
    function create_post_type() {
    	register_post_type( 'article',
    	array(
    		'hierarchical'=> false,
    		'labels' => array(
    		'name' => __( '記事追加' ),
    		'singular_name' => __( '記事追加' )
    		),
    		'public' => true,
    		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields' ,'comments' ),
    		'menu_position' =>5,
    	));
    	register_taxonomy('article-cat','article',
    			array(
          			'hierarchical' => true,
    				'label' => __('カテゴリ'),
    				'singular_label' => __('カテゴリ'),
    				'public' => true,
    				'show_ui' => true,
    			)
    	);
    }
    add_action( 'init', 'mytheme_add_rewrite_tag', 0 );
    function mytheme_add_rewrite_tag() {
     	global $wp_rewrite;
     	$queryarg = 'post_type=article&name=';
      	$wp_rewrite->add_rewrite_tag('%article_postname%', '([^/]+)', $queryarg);
      	$wp_rewrite->add_permastruct('article', '%article-cat%/%article_postname%', false);
    }
    add_filter('post_type_link', 'myposttype_permalink', 1, 3);
    function myposttype_permalink($post_link, $id = 0, $leavename) {
    	global $wp_rewrite;
    	$post = get_post($id);
    	if ( is_wp_error( $post ) ){
    		return $post;
    	}
    	if($post->post_type == 'article'){
    		$newlink = $wp_rewrite->get_extra_permastruct('article');
    		$newlink = str_replace('%article_postname%', $post->post_name, $newlink);
    		$newlink = home_url(user_trailingslashit($newlink));
    		return $newlink;
    	}else{
    		return $post_link;
    	}
    }
    add_filter( 'post_type_link', 'custom_term_link' , 1, 3 );
    function custom_term_link( $post_link, $id = 0 ) {
    	$post = get_post($id);
    	if ( is_wp_error($post) || 'article' != $post->post_type || empty($post->post_name) ){
    		return $post_link;
    	}
    	$terms = get_the_terms($post->ID, 'article-cat');
    	if( is_wp_error($terms) || !$terms ) {
    		$term_slug = 'uncategorised';
    	} else {
    		$term_obj = array_pop($terms);
    		$term_slug = $term_obj->slug;
    	}
    	return home_url(user_trailingslashit( "$term_slug/$post->post_name" ));
    }

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • モデレーター jim912

    (@jim912)

    mytheme_add_rewrite_tag の優先順序が 0で指定されているのに対し、create_post_type の優先順序がデフォルトの10なので、後から実行される register_post_type でのパーマリンク構造に上書きされてしまっています。

    なお、この事象が解消されると、URLからカスタム投稿と固定ページや投稿(パーマリンク設定による)との判別がつかなくなるため、固定ページ、投稿の個別投稿ページが404になります。

    トピック投稿者 kazaisyu

    (@kazaisyu)

    jim912さん、ありがとうございます。
    色々と考えてみたものの解決できそうになかったので、カスタム投稿を普通の投稿に(メニュー名を変えることでUIを改善)、それ以外をカスタム投稿に振り分けることで解決することにしました。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「カスタム投稿タイプとカスタム分類のパーマリンクで404に」には新たに返信することはできません。