所以在花了很多时间,尝试了很多不同的事情之后,我终于找到了正确的方法。我用过MonkeyMan Rewrite Analyzer 以及WP调试栏,以帮助了解如何构建重写。
因此,首先,我的自定义帖子类型URL被重写如下:
// Artist Rewrite Args
$rewrite = array(
\'slug\' => \'artist\',
\'with_front\' => true,
\'pages\' => true,
\'feeds\' => true,
);
// Portfolio Rewrite Args
$rewrite = array(
\'slug\' => \'portfolio\',
\'with_front\' => false,
\'pages\' => true,
\'feeds\' => true,
);
然后,我注册一个重写标记
%artistname%
艺术家的名字,我们将通过
WP_Query
函数,以及一个重写规则,用于填写艺术家姓名所占的段首,该段首字母将位于所显示的公文包段首字母之前。
// Portfolio Rewrite Rule
add_action( \'init\', \'portfolio_rewrite_tag\' );
function portfolio_rewrite_tag() {
add_rewrite_tag(\'%artistname%\',\'[^/]+\');
// defines the rewrite structure for \'portfolios\'
// says that if the portfolio URL matches this rule, then it should display the \'artists\' post whose post name matches the last slug set
add_rewrite_rule( \'^artist/[^/]+/([^/]+)/?$\',\'index.php?portfolio=$matches[1]\',\'top\' );
}
接下来,我改进了URL过滤器,以检查它是否是一个公文包帖子,如果是,则从第一个连接的帖子中抽取slug
artist
, 然后将弹头塞进链接后的字符串中。
// Grab connected artist name and swap it into the URL
function filter_portfolio_link( $post_link, $post ) {
if ( $post->post_type === \'portfolio\' ) {
$connected = new WP_query( array(
\'post_type\' => \'artist\',
\'connected_type\' => \'portfolios_to_artists\',
\'connected_items\' => $post,
\'nopaging\' => true,
) );
if ($connected->have_posts() ) {
$first = true;
foreach ( $connected as $connectedPost ) {
setup_postdata($connectedPost);
if ($connectedPost->post_type === \'artist\') {
if ($first) {
$artistName = $connectedPost->post_name;
$first = false;
}
}
}
$post_link = str_replace( \'portfolio\', \'artist/\' . $artistName, $post_link );
}
}
return $post_link;
}
add_filter( \'post_type_link\', \'filter_portfolio_link\', 10, 2);
就是这样!虽然我没有使用线程中讨论的相同插件
Nested custom post types with permalinks, 整个线索对得出这个结论非常有帮助。