Tre*_*man 5 php wordpress slug custom-fields custom-post-type
基本上我有一个名为"Parts"的自定义帖子类型设置,目前有超过5,000个帖子.每个部件都有许多自定义字段,包括"部件号".目前,每个部分的URL是:
http://site.com/parts/name-of-part/
我宁愿拥有的是:
http://site.com/parts/XXXX-608-AB/(这是一个部件号,存储为自定义字段"partno".)
我相信我需要做两件事:
1)根据自定义字段"partno"制作一个脚本,以批量编辑每个现有部件的所有slug.
2)连接到Wordpress函数以触发它始终根据自定义字段"partno"为新零件创建slug.
有没有人知道如何完成这些方面中的一个或两个?
更新:以下是我最终用于更改现有帖子的代码
// Set max posts per query
$max = 500;
$total = 5000;
for($i=0;$i<=$total;$i+=$max) {
$parts = get_posts(array('post_type' => 'parts', 'numberposts' => $max, 'offset' => $i));
// loop through every part
foreach ( $parts as $part ) {
// get part number
$partno = get_post_meta( $part->ID, 'partno', true );
$updated_post = array();
$updated_post['ID'] = $part->ID;
$updated_post['post_name'] = $partno;
wp_update_post( $updated_post ); // update existing posts
echo $part->ID;
}
}
Run Code Online (Sandbox Code Playgroud)
更新:以下是我在functions.php中用来更改正在发布的帖子的代码 (部分归功于https://wordpress.stackexchange.com/questions/51363/how-to-avoid-infinite-loop-in-save-post -callback)
add_action('save_post', 'my_custom_slug');
function my_custom_slug($post_id) {
//Check it's not an auto save routine
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
//Perform permission checks! For example:
if ( !current_user_can('edit_post', $post_id) )
return;
//If calling wp_update_post, unhook this function so it doesn't loop infinitely
remove_action('save_post', 'my_custom_slug');
//call wp_update_post update, which calls save_post again. E.g:
if($partno != '')
wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'partno',true)));
// re-hook this function
add_action('save_post', 'my_custom_slug');
}
Run Code Online (Sandbox Code Playgroud)
1) 创建一个新页面并为其分配一个新的页面模板,例如site.com/update和update.php。update.php 内部写入批量机制:
<?php // grab all your posts
$parts = get_posts(array('post_type' => 'parts', 'numberposts' => -1,))
// loop through every part
foreach ( $parts as $part ) {
// get part number
$partno = get_post_meta( $part->ID, 'parto', true );
$updated_post = array();
$updated_post['ID'] = $part->ID;
$updated_post['post_name'] = $partno;
wp_update_post( $updated_post ); // update existing posts
} ?>
Run Code Online (Sandbox Code Playgroud)
您可以将其放置在主题中的任何位置,但我喜欢为此创建一个页面,以便我可以轻松地使用它运行 cron 作业。
接下来是更改每个新创建的帖子的 slug 的函数:
<?php function change_default_slug($id) {
// get part number
$partno = get_post_meta( $id, 'parto', true );
$post_to_update = get_post( $id );
// prevent empty slug, running at every post_type and infinite loop
if ( $partno == '' || $post_to_update['post_type'] != 'parts' || $post_to_update['post_name'] == $partno )
return;
$updated_post = array();
$updated_post['ID'] = $id;
$updated_post['post_name'] = $partno;
wp_update_post( $updated_post ); // update newly created post
}
add_action('save_post', 'change_default_slug'); ?>
Run Code Online (Sandbox Code Playgroud)
每次保存帖子时(例如第一次发布时),上面的代码都会运行,并将新的 post_name 设置为零件号。