Create a custom location rule ‘Post Has Parent’ for WordPress Advanced Custom Fields

Create an ACF rule to restrict display of custom fields on the edit page based on whether or not the post has ancestors.

Create rule

<!-- FILENAME: './includes/class-acf-location-post-has-parent.php' -->

<?php 

if( ! defined( 'ABSPATH' ) ) exit;

class ACF_Location_Post_Has_Parent extends ACF_Location {

  public function initialize() {
    $this->name = 'post_has_parent';
    $this->label = __( "Post Has Parent", 'acf' );
    $this->category = 'post';
    $this->object_type = 'post';
  }

  public function get_values( $rule ) {
    $choices = array(1 => "True", 0 => "False");

    return $choices;
  }

  public function match( $rule, $screen, $field_group ) {

    // Check screen args for "post_id" which will exist when editing a post.
    // Return false for all other edit screens.
    if( isset($screen['post_id']) ) {
      $post_id = $screen['post_id'];
    } else {
      return false;
    }

    // Load the post object for this edit screen.
    $post = get_post( $post_id );
    if( !$post ) {
      return false;
    }

    // Compare the Post's attribute to rule value.
    // cannot simply use true/false as the post_parent field returns an id not a boolean
    $result = ($rule['value'] == 0) ? ( $post->post_parent == $rule['value'] ) : ( $post->post_parent > 0 );

    // Return result taking into account the operator type.
    if( $rule['operator'] == '!=' ) {
      return !$result;
    }
    return $result;
  }
}Code language: PHP (php)

Add action

<!-- functions.php -->

...

// ACF custom location type to check if a page has a parent
add_action('acf/init', 'acf_init_location_types');
function acf_init_location_types() {
  // Check function exists, then include and register the custom location type class.
  if( function_exists('acf_register_location_type') ) {
    include_once( 'includes/class-acf-location-post-has-parent.php' );
    acf_register_location_type( 'ACF_Location_Post_Has_Parent' );
  }
}

...Code language: PHP (php)
References

ACF Docs

WordPress WP_Query Docs

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.