php - 通过保存/更新时的自定义字段动态更改帖子永久链接
问题描述
我想在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');
}
解决方案
我会对此进行破解...
现在,这是假设您将 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;
}
}
推荐阅读
- matlab - MATLAB:如何根据与视频同步的时间和时间显示数值?
- html - 如何将标题徽标与菜单对齐?
- android - 获取 RoomDatabase 实例的单例设计模式
- r - 循环两个相同大小的数据帧并计算相关性
- swift - 应用程序在 Xcode 中运行良好,但从导出运行时出错
- android - 创建裁剪位图而不创建新位图
- c++ - 当我们在数组中没有找到搜索的项目时,为什么我们使用 if(i==n-1) 条件?它是如何工作的?
- saml-2.0 - 能否 ping federate 支持具有多个 IssuerID 的 SP
- python - 使用 Python 连接到数据集的 Power BI XMLA 端点
- sql - 如何将多个键值对选择到单个列中?