我有很多相同标题的帖子(房产),我需要在发布新帖子后创建单个房产的url->标题+ID(ID部分,自动添加)。
有没有可能改变现有的?(我已经创建了很多)
请帮帮我,我卡住了
我有很多相同标题的帖子(房产),我需要在发布新帖子后创建单个房产的url->标题+ID(ID部分,自动添加)。
有没有可能改变现有的?(我已经创建了很多)
请帮帮我,我卡住了
是的,这实际上是Wordpress自动为您所做的。
导航到Settings>Permalinks 并添加所需的自定义结构,如:
/%postname%-%post_id%/
保存帖子url时,此代码将更新帖子url:
function wpse_288020_replace_url( $post_id ) {
$post_type = get_post_type( $post_id );
if( $post_type === \'your_post_type\' ) {
$title = get_the_title( $post_id );
$title = sanitize_title( $title );
$post = array(
\'ID\' => $post_id,
\'post_name\' => sprintf(\'%s-%s\', $title, $post_id),
);
remove_action( \'save_post\', \'wpse_288020_replace_url\' ); // Remove action to prevent loop
wp_update_post( $post );
add_action( \'save_post\', \'wpse_288020_replace_url\' );
}
}
add_action( \'save_post\', \'wpse_288020_replace_url\' );
此代码将对您的所有帖子URL进行大规模更新:function wpse_288020_batch_replace_url() {
// Get all posts
$query = new WP_Query(array(
\'post_type\' => \'post\',
\'posts_per_page\' => -1,
));
$posts = $query->get_posts();
foreach ($posts as $post) {
// Get permalink
$title = sanitize_title($post->post_title);
// Prepare arguments
$args = array(
\'ID\' => $post->ID,
\'post_name\' => sprintf(\'%s-%s\', $title, $post->ID),
);
// Update post
wp_update_post( $args );
}
}
add_action(\'init\', \'wpse_288020_batch_replace_url\');
如果有许多帖子,请通过添加WP_POST_REVISIONS
常数至wp-config.php
. 它将加快脚本速度并减少对内存使用的需求。define( \'WP_POST_REVISIONS\', false );
打印准备好的查询时,我看到以下字符串:\"SELECT p.ID, COALESCE(w.value,Display_name) value, p.post_title, p.post_date, p.post_content,p.post_author,user_login FROM wp_posts p INNER JOIN wp_users a ON a.ID = p.post_author LEFT JOIN wp_bp_xprofile_data w ON w.user_id = a.ID WH