首页 > 解决方案 > 通过保存/更新时的自定义字段动态更改帖子永久链接

问题描述

我想在post_name每次保存/更新帖子时动态更改 WordPress 帖子的永久链接 (),方法是从帖子中存在的自定义字段中提取并用该值替换永久链接。我有代码在functions.php其中工作,除了它附加-2到永久链接。我认为这是因为某些事情发生了两次,第一次导致我想要的永久链接,第二次导致 WordPress 通过添加-2.

这是当前代码:

add_action('save_post', 'change_default_slug');

function change_default_slug($post_id) {

if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
return;

if ( !current_user_can('edit_post', $post_id) ) 
return;

remove_action('save_post', 'change_default_slug');

wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'request_number',true)));;

add_action('save_post', 'change_default_slug');
}

标签: phpwordpressadvanced-custom-fieldscustom-fields

解决方案


我会对此进行破解...

现在,这是假设您将 ACF 用于您的自定义字段...如果没有,只需使用 WP 自定义元函数更新代码。哦,别忘了用你的 ACF 字段键更改 field_5fed2cdbc1fd2

add_filter('save_post', 'change_post_name', 20, 1);
function change_post_name($post_id)
{

  $post_type = get_post_type();
  if ($post_type == "post"){

                
     $acf_title_field = $_POST['acf']['field_5fed2cdbc1fd2']; // get the field data by $_POST

    if (!empty($acf_title_field)) {

        // update the title in database
        $wpdb->update($wpdb->posts, array('post_title' => $acf_title_field, 'post_name' => sanitize_title($acf_title_field)), array('ID' => $post_id));  

    }
  }
}

add_filter( 'wp_insert_post_data', 'update_post_name', 50, 2 );
function update_post_name( $data, $postarr ) {
    $post_type = get_post_type();
    if ($post_type == "post"){
        //Check for the  post statuses you want to avoid
        if ( !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {  

            $acf_title_field = $_POST['acf']['field_5fed2cdbc1fd2']; // get the field data by $_POST
            // $data['post_name'] = sanitize_title( $data['post_title'] );
            $data['post_name'] = sanitize_title( $acf_title_field );

        }
    return $data;
    }
}


推荐阅读