Support

Account

Forum Replies Created

  • Thanks! Maybe I’m doing something wrong? It seems like the fixes I implement on templates don’t impact the notices. But I also tried opting into the HTML escaping using this snippet:

    add_filter( 'acf/the_field/escape_html_optin', '__return_true' );

    And everything seemed to work correctly on the front end.

  • Yes, I did get some more info on this. Dismissing the admin notice will clear out the log. But the notice will keep coming back if there are fields that will be escaped due to the update.

    I’ve changed several templates to use:

    echo get_field('field_name');

    The notice still shows up. I’m guessing that ACF isn’t necessarily looking for this code at the template level, just the contents of the field.

  • Thanks, John I’ll do that!

  • I’m getting the very same issue here on WP 5.5.3. I can add a new block and it shows up just fine, but existing ACF blocks on a page won’t load on the back end.

  • Problem solved – I was querying the wrong post type πŸ™‚

  • Just wanted to throw my 2 cents in there – I’m running into the same issue as well with draft posts in preview.

  • Thanks James! I have gone through these steps but am still having a bit of trouble. I submitted a ticket (not sure if this issue can be handled further by an official ticket, but figured it was worth a shot).

    Seems like the issue I’m having at this point is that a post object isn’t assigned a value, thus the conditional for preexisting posts never fires.

  • I think I’ve got just about everything down with this. Just one more thing I have to wrestle with (I think, I hope).

    The way I have this setup on the backend is that I have a custom post type called “Daily News Briefs”. The author can go in and write whatever they want in the standard WP content editor for that post, and then use the code we’ve been working on to create multiple “sub-posts” with the repeater fields. Those new posts are just saved as standard WP Posts.

    In the original code you so kindly fashioned, there is this:

    // delete the unused post
        wp_delete_post($post_id);

    I’ve commented that out because, in my case, I want to keep that post I’ve created in the custom post type.

    The only other issue I can find here is that, if I were to go into that custom post type and edit one of the custom fields and re-save, I’ll get a whole other set of duplicate posts created.

    What I’ve tried to do is write a conditional that says if the post_id exists, simply update it using wp_update_post, otherwise use wp_insert_post. Unfortunately, that just leads to a duplicate post when trying to update.

    Here’s what I’m working with:

    // Special ACF Function for Creating Multiple Daily News Brief Posts
    function my_acf_save_multiple_posts( $post_id ) {
        
        // get the repeater
        $values = get_field('new_daily_brief_posts', $post_id);
    
        
        // loop through the repeater
        foreach( $values as $value ) {
    		
    		// set the new post arguments
            $new_post_article = array(
                'post_title' => $value['post_title'],
                'post_content' => $value['post_content'],
                'post_type' => 'post',
    			'post_status'	=> 'publish',
    			'tags_input' => $value['post_tags']
            );
            
    		// remove action to avoid infinite loop issue
    		remove_action('acf/save_post', 'my_acf_save_multiple_posts', 20);
    		
    		// look to see if this post already exists
    		$exists =  get_post_status ( $ID ) == 'publish'; 
    		
    		// if this doesn't exist, create the post.
    		if( !$exists ){
    
     		// post it!
            $new_brief_post_id = wp_insert_post($new_post_article);
    		
    		}
    		
    		// Update the post if it already exists
    		else {
    			
    		// remove action to avoid infinite loop issue
    		
    	    $new_brief_post_id = wp_update_post($new_post_article);  }
    
    	}
        
        // delete the unused post
        //wp_delete_post($post_id);
    
    }
    
    // run after ACF saves the $_POST['acf'] data
    add_action('acf/save_post', 'my_acf_save_multiple_posts', 20);

    I would imagine that acf/safe_post would interfere with updating the post?

  • James, it worked! If we ever meet, you are getting an entire case of beer on me πŸ™‚

  • One thing I have noticed is that, when using this on the back end, it creates duplicates of each post. Any reason you can think of that this would happen? I’m not using acf_form on the back end but wasn’t sure if that was necessary since it does create the post.

  • James, I can’t thank you enough! That worked perfectly πŸ™‚

    I am a loyal Pro user because it’s an amazing plugin and you provide such outstanding support. Thank you.

  • Thanks James! It’s really weird, I’m starting to wonder if the functions.php code is firing at all. I’ve made changes and thought it looked good, but still no luck. All I get is a completely blank post that I can’t delete from the dashboard. I did update the code to the following…

    Template:

    <?php
    		
    		// Bail if not logged in or able to post
        if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
            echo '<p>You must be a registered author to post.</p>';
            return;
        }
    		
    		 acf_form(array(
    					'post_id'		=> 'new_post',
    					'field_groups' => array(4)
    				));
    			
    				
    				 ?>

    Functions.php
    // Special ACF Function for Creating Multiple Daily News Brief Posts
    // This function imports multiple posts at once

    function acf_import_multiple_posts( $post_id ) {
    	
    	
      // If the post_id is not equal to 'new', skip the entire function
      if( $post_id != 'new_post' ) {
      return $post_id;
      };
    
      $loop = $_POST['acf']['field_57614ac1e5179']; //ACF Repeater Field key
      $customMetaField = 'news_post_tags'; // Custom Meta Field
      $customContentField = 'news_post_content'; // Custom Content Field
      $customPostTitle = 'news_post_title'; // Custom Title
    
      $count = count($loop); // Get the number of rows in the Repeater Field
    
      for ($key = 0; $key < $count; ++$key) { // If $count is 5, run for loop till it reaches 5 times
        // Swap out $key for each row number
        $customMetaField = trim($_POST['acf']['field_5762b0a5ad19f'][$key]['field_5762b0a5ad19f']);
        $customContentField = trim($_POST['acf']['field_57614bf6c6b13'][$key]['field_57614bf6c6b13']);
        $customPostTitle = trim($_POST['acf']['field_57614baac6b12'][$key]['field_57614baac6b12']);
    
        // Create a new App Post from posts listed in the repeater field
        $post = array(
          'post_status'  => 'publish', // Set to draft because the user still needs to review
          'post_title' => $customPostTitle, // Actual Post Title
          'post_name' => sanitize_title( $customPostTitle ), // Actual Post Slug
    	  'post_content' => $customContentField, // Post Content
          'post_type'  => 'post' // Post Type
        );
    
        $post_id = wp_insert_post( $post );     // Use the WordPress default wp_insert_post function
    
        // Set the Custom Meta Fields with the $customMetaField, $customContentField and $customPostTitle
        add_post_meta($post_id, 'news_post_tags', $customMetaField, true);
    	add_post_meta($post_id, 'news_post_content', $customContentField, true);
        add_post_meta($post_id, 'news_post_title', $customPostTitle, true);
      }
    
      // update $_POST['return']
      $_POST['return'] = add_query_arg( array('post_id' => $post_id), $GLOBALS['acf_form']['return'] );
    
      // return the new ID
      return $post_id;
    }
    
    add_action('acf/pre_save_post', 'acf_import_multiple_posts', 20);
  • I’ve given this a shot (just testing it on the front end before I figure out how to add it on the back end) and I can create a single, untitled post with no content πŸ™‚

    Here’s what I’ve got in the front end template:

    <?php
    		
    		// Bail if not logged in or able to post
        if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
            echo '<p>You must be a registered author to post.</p>';
            return;
        }
    		
    		 acf_form(array(
    					'post_id'		=> 'new_post',
    					'form'               => true,
    					'field_groups' => array(4),
    					'new_post'		=> array(
    						'post_type'		=> 'post',
    						'post_status'		=> 'publish'
    					),
    					'submit_value'		=> 'Save Posts',
    					'updated_message' => __("Post updated", 'acf')
    				));
    				
    				 ?>

    And in functions.php…

    // Special ACF Function for Creating Multiple Daily News Brief Posts
    // This function imports multiple posts at once
    function acf_import_multiple_posts( $post_id ) {
      // If the post_id is not equal to 'new', skip the entire function
      if( $post_id != 'new' ) {
        return $post_id;
      };
    
      $loop = $_POST['acf']['field_57614ac1e5179']; //ACF Repeater Field key
      $customMetaField = 'news_post_tags'; // Custom Meta Field
      $customContentField = 'news_post_content'; // Custom Content Field
      $customPostTitle = 'news_post_title'; // Custom Title
    
      $count = count($loop); // Get the number of rows in the Repeater Field
    
      for ($key = 0; $key < $count; ++$key) { // If $count is 5, run for loop till it reaches 5 times
        // Swap out $key for each row number
        $customMetaField = trim($_POST['acf']['field_5762b0a5ad19f'][$key]['field_5762b0a5ad19f']);
        $customContentField = trim($_POST['acf']['field_57614bf6c6b13'][$key]['field_57614bf6c6b13']);
        $customPostTitle = trim($_POST['acf']['field_57614baac6b12'][$key]['field_57614baac6b12']);
    
        // Create a new App Post from posts listed in the repeater field
        $post = array(
          'post_status'  => 'publish', // Set to draft because the user still needs to review
          'post_title' => $customPostTitle, // Actual Post Title
          'post_name' => sanitize_title( $customPostTitle ), // Actual Post Slug
    	  'post_content' => $customContentField, // Post Content
          'post_type'  => β€˜post’ // Post Type
        );
    
        $post_id = wp_insert_post( $post );     // Use the WordPress default wp_insert_post function
    
        // Set the Custom Meta Fields with the $customMetaField, $customContentField and $customPostTitle
        add_post_meta($post_id, 'customMetaField', $customMetaField, true);
    	add_post_meta($post_id, 'customContentField', $customContentField, true);
        add_post_meta($post_id, 'customPostTitle', $customPostTitle, true);
      }
    
      // update $_POST['return']
      $_POST['return'] = add_query_arg( array('post_id' => $post_id), $GLOBALS['acf_form']['return'] );
    
      // return the new ID
      return $post_id;
    }
    add_action('acf/pre_save_post', 'acf_import_multiple_posts', 20);

    I know I’m doing something very wrong, but I’m just not sure what. Anything in particular stand out? Thanks so much for your help!

  • Thanks James! Good to know I’m on the right path πŸ™‚ Please excuse the questions, but I’m not an expert at PHP. The main things I’m wondering about at this point:

    -Do the field names have to be anything specific?

    -Any differences because I’m doing this on the back end, rather than the front end?

  • John, you’re a genius (even if you didn’t realize it)! That code did the trick:
    http://njcai.pairserver.com/tag/asphaltmaintenanceseal-coating/

    What I ended up with is:

    <?php 
    // Get the logo, if it exists.
    if( get_field('sponsor_logo') ):
    $image = get_field('sponsor_logo');
    if (intval($image) == $image) {
      $image = wp_get_attachment_image_src(intval($image), 'full');
      $image = $image[0];
    }
    ?>
    <img class="sponsorlogo" src="<?php echo $image ; ?>" width="120" height="120" alt="<?php the_field('sponsor_company_name'); ?>">
    <?php endif; ?>

    Thanks so much for your help with this!

  • Technically it could work that way. In this case, I’m not actively using the regular Posts area at all.

  • I went in and disabled everything except ACF and Custom Post Type UI (since I’m using this for the custom post type) and the problem is still there. However, it made me think of what I had to do to get the tag archives working in the first place. Apparently there is an issue with WordPress archives grabbing tags from custom posts types, so I had to use this code in my functions.php file:

    //Tag Archive
    function namespace_add_custom_types( $query ) {
      if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
        $query->set( 'post_type', array(
         'post', 'nav_menu_item', 'sponsors'
    		));
    	  return $query;
    	}
    }
    add_filter( 'pre_get_posts', 'namespace_add_custom_types' );

    And, for the heck of it, here are the other custom scripts I’m running in the functions.php file:

    /*
    * Allows extra HTML items in to the_excerpt instead of stripping them like WordPress does
    */
    function theme_t_wp_improved_trim_excerpt($text) {
    global $post;
    if ( '' == $text ) {
    $text = get_the_content('');
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text);
    $text = strip_tags($text, '<p>,<ul>,<li>,<ol>,<b>,<strong>,<br>,<a>,<br />');
    $excerpt_length = 70;
    $words = explode(' ', $text, $excerpt_length + 1);
    if (count($words)> $excerpt_length) {
    array_pop($words);
    array_push($words, '[...]');
    $text = implode(' ', $words);
    }
    }
    return $text;
    }
    
    remove_filter('get_the_excerpt', 'wp_trim_excerpt');
    add_filter('get_the_excerpt', 'theme_t_wp_improved_trim_excerpt');
    
    //Drop Down Menu for Tags
    function drop_tags()
    {
    echo "<select class=taglist onChange=\"document.location.href=this.options[this.selectedIndex].value;\">";
    echo "<option>Select a Category:</option>\n";
    foreach (get_tags() as $tag)
    {
    echo "<option value=\"";
    echo get_tag_link($tag->term_id);
    echo "\">".$tag->name."</option>\n";
    }
    echo "</select>";
    }
    
    // Custom Footer Menu Walker
    class example_nav_walker extends Walker_Nav_Menu {
    
        var $current_menu = null;
        var $break_point  = 6;
    
        function start_el(&$output, $item, $depth, $args) {
    
            global $wp_query;
    
            if( !isset( $this->current_menu ) )
                $this->current_menu = wp_get_nav_menu_object( $args->menu );
    
            if( !isset( $this->break_point ) )
                $this->break_point = ceil( $this->current_menu->count / 2 ) + 1;    
    
            $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    
            $class_names = $value = '';
    
            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
            $classes[] = 'menu-item-' . $item->ID;
    
            $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
            $class_names = ' class="' . esc_attr( $class_names ) . '"';
    
            $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
            $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
    
            if( $this->break_point == $item->menu_order )
                $output .= $indent . '</li></ul><ul id=menu-main-menu-2><li' . $id . $value . $class_names .'>';
            else
                $output .= $indent . '<li' . $id . $value . $class_names .'>';
    
            $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
            $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
            $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
            $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
    
            $item_output = $args->before;
            $item_output .= '<a'. $attributes .'>';
            $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;
    
            $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
        }
    }
    
    I'm not certain that this is the cause of the conflict, but I figured it would be relevant since it's helping create the archive pages.
  • Hi John, thanks for your help! So, I noticed I had an inconsistency here with the field name:

    <?php 
    // Get the logo, if it exists.
    $image = get_field('sponsor-logo');
    if( get_field('sponsor_logo') ): ?>

    Having fixed that and changing the image tag to your suggestion now seems to put the image ID in the SRC – for example:

    <img class="sponsorlogo" src="266" width="120" height="120" alt="Hillcrest Paving & Excavating">

    I’ve checked the field setup itself and it is set to output a URL, and does so in other templates. I’m guessing that because this template is for tags of a custom post type, it might require something else?

  • ractoon, thanks for your help! That code led me in the right direction. I did end up having to use 2 queries.

    First I checked for department heads:

    <?php //Get the Department Head First ?>
    <?php
    $args = array(
    	'numberposts' => -1,
    	'post_type' => 'staff',
    	'meta_key' => 'dir-department-head',
    	'meta_value' => 'yes'
    
    );
    query_posts($args);
    ?>
    	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
     
    <?php if (in_array("Administration", (array) get_field('dir-department')) AND ('yes' == get_field('dir-department-head'))): ?>

    Formatting fields, etc.

    <?php endif; ?> 
    <?php endwhile; endif; ?>
    <?php wp_reset_query(); ?>

    Then, a separate query for the rest of the employees, excluding the “yes” answers in the department head field by pulling only those entries who left the field blank:

    <?php // Get Other Deparment Employees ?>
    <?php
    $args = array(
    'post_type' => 'staff',
    'posts_per_page' => -1,
    'meta_key'	=> 'dir-last-name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
    );
    query_posts($args);
    ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php if (in_array("Administration", (array) get_field('dir-department')) AND ('' == get_field('dir-department-head'))): ?>

    Formatting fields, etc.

    <?php endif; ?> 
    <?php endwhile; endif; ?>
    <?php wp_reset_query(); ?>

    Thanks for leading me in the right direction!

  • Thanks! I have thought about doing 2 queries but I’m trying to salvage the setup of the their template if possible.

    Right now I’ve got a query like this:

    <?php
    $args = array(
    'post_type' => 'staff',
    'posts_per_page' => -1,
    'meta_key'	=> 'dir-last-name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
    );
    query_posts($args);
    ?>

    So that is grabbing everyone’s last name and sorting it. The template also has this bit of code, which I’m hoping to modify:

    <?php if (in_array("Administration", (array) get_field('dir-department'))): ?>

    In this bit, it’s looking for entries in the Administration department. Code below that (not included here) formats the entry nicely.

    What I would love to do is modify this to also look for a value of “yes” in the ‘dir-department-head’ field. So I want to look for someone in the Administration department (like the code above) and then also check to see if they are a Department Head. Basically an if/else statement that checks for a Department Head, then moves on to the rest of the list.

    I know only enough PHP to be dangerous so everything I’ve tried to do doesn’t seem to work πŸ˜‰

  • fazedesigns, thank you! I just got into a similar situation and your tip saved me so much time.

  • Eventually figured this out! FYI, here’s the code in case it helps anyone. The name of my WYSIWYG field is ‘about_this_product_category’, which you would replace with your own field name.

    <?php 
     
    // vars
    $queried_object = get_queried_object(); 
    $taxonomy = $queried_object->taxonomy;
    $term_id = $queried_object->term_id;  
     
    // load desc for this taxonomy term (term object)
    $thumbnail = get_field('about_this_product_category', $queried_object);
     
    // load desc for this taxonomy term (term string)
    $thumbnail = get_field('about_this_product_category', $taxonomy . '_' . $term_id);
    
    ?>    
    
    <?php the_field( 'about_this_product_category', $queried_object ); ?>  

    I copied the archive-product.php from the WooCommerce plugin directory into a new /woocommerce/ folder inside my theme.

Viewing 22 posts - 1 through 22 (of 22 total)