我正在尝试更改自定义帖子类型帖子的url结构,但目前无法正常工作。
我想做的是通过函数更改自定义帖子类型(测试)帖子的URL。php。通过使用post\\u type\\u link和add\\u rewrite\\u rule,我想将%hallo%重写为自定义字段值(通过使用get\\u post\\u meta)。我希望有人能帮我解决这个问题。我已经尝试了几十种方法,但仍然不起作用。
在管理方面,我现在的工作正常。它以我希望的方式显示URL(domain.com/test/mycustomfieldvalue/post title/)。当我想在前端查看页面时,就会出现问题。我得到一个400 Bad Request error 我可以看到我的url已更改为domain.com/test/%hallo%/post-title/.
Note: 我知道在更改URL时需要刷新重写规则。我现在经常使用flush\\u rewrite\\u rules()进行测试,所以这不是问题所在。
请看下面我的代码。
My custom post type
add_action( \'init\', \'cpt_test_init\' );
function cpt_test_init() {
$labels = array(
\'name\' => _x( \'Test\', \'post type general name\', \'mytheme\' ),
\'singular_name\' => _x( \'Test\', \'post type singular name\', \'mytheme\' ),
\'menu_name\' => _x( \'Test\', \'admin menu\', \'mytheme\' ),
\'name_admin_bar\' => _x( \'Test\', \'add new on admin bar\', \'mytheme\' ),
\'add_new\' => _x( \'Nieuwe test toevoegen\', \'faq\', \'mytheme\' ),
\'add_new_item\' => __( \'Nieuwe test toevoegen\', \'mytheme\' ),
\'new_item\' => __( \'Nieuwe test\', \'mytheme\' ),
\'edit_item\' => __( \'Test aanpassen\', \'mytheme\' ),
\'view_item\' => __( \'Bekijk test\', \'mytheme\' ),
\'all_items\' => __( \'Alle test\', \'mytheme\' ),
\'search_items\' => __( \'Test zoeken\', \'mytheme\' ),
\'parent_item_colon\' => __( \'Bovenliggend item:\', \'mytheme\' ),
\'not_found\' => __( \'Geen test gevonden.\', \'mytheme\' ),
\'not_found_in_trash\' => __( \'Geen test gevonden in de prullenbak.\', \'mytheme\' )
);
$args = array(
\'labels\' => $labels,
\'description\' => __( \'Description.\', \'mytheme\' ),
\'public\' => true,
\'publicly_queryable\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'query_var\' => true,
\'rewrite\' => array( \'slug\' => \'test/%hallo%\', \'with_front\' => false ),
\'capability_type\' => \'post\',
\'has_archive\' => false,
\'hierarchical\' => false,
\'menu_position\' => NULL,
\'supports\' => array( \'title\', \'revisions\' )
);
register_post_type( \'test\', $args );
}
How I\'m trying to change the urls
function change_test_links( $post_link, $post, $leavename ) {
if ( is_object( $post ) && $post->post_type == \'test\' ) {
$metaText = get_post_meta(get_the_ID(), \'test_text_field\', true);
if ( $metaText ) {
return str_replace( \'%hallo%\', $metaText, $post_link );
}
}
return $post_link;
}
add_filter( \'post_type_link\', \'change_test_links\', 1, 3 );
function test_rewrite_rules() {
add_rewrite_rule(
\'^test/(.*)/(.*)/?$\',
\'index.php?post_type=test&name=$matches[2]\',
\'top\'
);
}
add_action( \'init\', \'test_rewrite_rules\' );
我真的希望有人能帮我。我觉得我很接近,或者我错过了一些简单的事情。提前感谢!
Edit: 当我尝试将%hallo%重写为硬编码字符串(例如“mynewtext”)时,一切都正常。所以我猜我的问题是使用get\\u post\\u meta。
是否有效:
return str_replace( \'%hallo%\', \'mynewtext\', $post_link );
不起作用:
$metaText = get_post_meta(get_the_ID(), \'test_text_field\', true);
return str_replace( \'%hallo%\', $metaText, $post_link );