wordpress - 如果自定义字段等于页面标题,则自动选择父页面
问题描述
当自定义字段和页面标题相等时,是否可以在页面创建时自动设置/选择父页面?
例子:
我有以下页面层次结构:
- 提供者
- 提供者页面(页面标题 = user1)
- 提供程序包
- 提供者页面(页面标题 = user1)
创建新页面时,自定义字段值为“user1”,并且有一个标题为“user1”的页面。然后提供者页面,在本例中为“user1”,应自动设置为所创建页面(提供者包页面)的父级。
我希望它有点清楚,因为我注意到自己很难解释。
这样的事情可能吗?
解决方案
您可以通过使用后期编辑挂钩过滤器/操作来实现此目的。像这样
add_action( 'edit_post', 'parentsetter_save_post' );
function parentsetter_save_post()
{
global $post;
$custom_field=get_post_meta($post->ID,'customfieldname',true);
if ($custom_field!=''){
$parent_page=get_page_by_title($custom_field);
if (!empty($parent_page) and $post->post_parent!=$parent_page->ID){
global $wpdb;
$wpdb->query($wpdb->prepare("update $wpdb->posts set post_parent=%d
where ID=%d",$parent_page->ID,$post->ID));
}
}
}
只需将“customfieldname”替换为您的自定义字段名称即可。
推荐阅读
- c++ - 数组操作在插入后和执行一个操作循环退出后面临数组大小变化的问题
- javascript - 如何在提交时使用 jquery 验证来验证表单?
- python-3.x - 如何划分对象列表中的两个元素?
- reactjs - 如何防止 react-router-dom 嵌套路由与路由参数混淆
- tron - 如何使用 trongrid api 过滤器参数获取合同事件?
- css - 如何在所有屏幕中增加 div 高度?
- git - Github 上的双重用户名
- python - 有没有办法使用熊猫根据其他条件从两个不同的列和跨行对日期进行分组?
- java - KubernetesClientException:操作:[list] for kind:[Endpoints] with name: [null] in namespace: [null] failed
- flutter - DART:显示选定的联系人