首页 > 解决方案 > 如果自定义字段等于页面标题,则自动选择父页面

问题描述

当自定义字段和页面标题相等时,是否可以在页面创建时自动设置/选择父页面?

例子:

我有以下页面层次结构:

创建新页面时,自定义字段值为“user1”,并且有一个标题为“user1”的页面。然后提供者页面,在本例中为“user1”,应自动设置为所创建页面(提供者包页面)的父级。

我希望它有点清楚,因为我注意到自己很难解释。

这样的事情可能吗?

标签: wordpressparent-childparentadvanced-custom-fieldspage-title

解决方案


您可以通过使用后期编辑挂钩过滤器/操作来实现此目的。像这样

 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”替换为您的自定义字段名称即可。


推荐阅读