Support

Account

Home Forums Front-end Issues Setting Parent Posts from Frontend Reply To: Setting Parent Posts from Frontend

  • To set the parent post from the front end you need a relationship field that is only available on the front end. Set this up to start. Add a post object field that only allows one selection.

    Create the following filters for your field in functions.php

    
    // only show field on front of site
    // https://www.advancedcustomfields.com/resources/acf-prepare_field/
    add_filter('acf/prepare_field/name=YOUR FIELD NAME HERE', 'field_only_on_front');
    function field_only_on_front($field) {
      if (is_admin()) {
        return false;
      }
      return $field;
    }
    
    // alter the acf query of the post object field to only show top level posts
    https://www.advancedcustomfields.com/resources/acf-fields-post_object-query/
    add_filter('acf/fields/post_object/query/name=YOUR FIELD NAME HERE', 'only_top_level_posts', 20, 3);
    function only_top_level_posts($args, $field, $post_id) {
      $args['post_parent'] = 0;
      return $args;
    }
    

    After you do this set up your taxonomy field to return term objects

    Once all that is done then then create an acf/save_post filter in functions.php

    
    add_action('acf/save_post', 'update_and_save_journal_post');
    function update_and_save_journal_post($post_id) {
      // make sure to only do this on the right post type
      $post_type = get_post_type($post_id);
      if ($post_type != 'YOUR POST TYPE HERE') {
        return;
      }
      // get the post
      $post = get_post($post_id);
      // get the parent, unformatted, ID only
      $parent = get_field('YOUR POST OBJECT FIELD', $post_id, false);
      if ($parent ) {
        $post->post_parent = $parent;
      }
      
      // get the taxonomy field
      $terms = get_field('YOUR TAXONOMY FIELD;, $post_id);
      if (!empty($terms) && !is_wp_error($terms)) {
        $term = terms[0];
        $post->post_title = $term->name.$post->post_title;
      }
      // remove this action so that an infinite loop is not created
      remove_filter('acf/save_post', 'update_and_save_journal_post');
      // update the post
      wp_update_post($post);
      // re-add this filter
      add_action('acf/save_post', 'update_and_save_journal_post');
    }
    

    Please note that none of the above code has been tested for syntax errors.