Support

Account

Home Forums General Issues CPT child of Page selected using ACF

Unread

CPT child of Page selected using ACF

  • Hi,

    I’m trying to change the permalink of my CPT ‘book-name’ by making it the child of a default page ‘genre-name’. I’m using ‘Post Object’ from ACF to select the page that will become the parent of the CPT.

    So in the CPT I will have a selector for the parent page – ‘genre-name’.

    The problem is that ACF is returning a wp_post object. How can I work with this in order to make the change on the permalink and to make it the parent of my CPT?

    I followed a tutorial that was using meta boxes, but I’m lost now….

    Tried a lot of things, this is what I have now:

    function rewrite_url_for_books() {
      add_rewrite_tag('%book%', '([^/]+)', 'book=');
      add_permastruct('book', '/%genre%/%book%', false);
      add_rewrite_rule('^([^/]+/([^/]+/?', 'index.php?book=$matches[2]', 'top');
    }
    
    add_action( 'init', 'rewrite_url_for_book' );
    
    function permalink_for_book($permalink, $post, $leavename) {
      $post_id = $post->ID;
      if($post->post_type != 'book' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
        return $permalink;
    
      $genre = get_field('genre_field');
      setup_postdata($genre);
    
      $parent = $post->post_parent;
      $parent_post = get_post($parent);
    
      $permalink = str_replace('%genre%', $parent_post->post_name, $permalink);
    
      return $permalink;
    }
    
    add_filter('post_type_link', 'permalink_for_book', 10, 3);

    Thank you!

Viewing 1 post (of 1 total)

The topic ‘CPT child of Page selected using ACF’ is closed to new replies.