Kriuchko
1/8/2019 - 2:53 PM

Add fields on create post добавление кастомфилдов при создании поста on add post

Wordpress add fields on create post

<?php $info = apply_filters('get_the_content', get_post_meta(get_the_ID(), 'how-we-help', true)); if(!empty($info)){ echo $info; } ?>

<?php $video = apply_filters('the_content', get_post_meta(get_the_ID(), 'video', true)); if(!empty($video)){ echo '<div class="video-holder">'.$video.'</div>'; } ?>

<?php $variable = get_field('field_name', 'product-cat_23'); ?>

<?php $contactphone = get_field('contact_phone','option'); ?>

<p><?php the_field('field_name', 'category_7'); ?></p>

<p><?php the_field('field_name', 'user_1'); ?></p>
Вместо имени подставь ключ если выбираешь для пользователя

$value = get_field( "text_field", get_the_ID()); 

апдейтит поле Post Object поста
update_field( 'field_55bb9faef8645', array(56), $post_id);

\!h получить все значения кастомфилда

<?php 
    $field = get_field_object('phu_de','114');
    
    if( $field )
    {
      foreach( $field['choices'] as $k => $v )
      {
        echo 'key:' . $k . 'value:' . $v;
      }
    }
  ?>

\!h acf link

<?php if( $cf_tab_link ): ?>
    <a href="<?php echo $cf_tab_link['url']; ?>" class="btn-link" <?php if( $cf_tab_link['target'] ): ?>target="<?php echo $cf_tab_link['target']; ?>"<?php endif; ?>>
        <?php echo $cf_tab_link['title']; ?>
    </a>
<?php endif; ?>


\!h acf repeater

<?php if( have_rows('testimonials') ): ?>
<div class="blockquote-section">
  <div class="container">
    <div class="blockquote-slider">
      <?php
      while( have_rows( 'testimonials' ) ): the_row();
        $image = get_sub_field( 'image' );
        $text = get_sub_field( 'text' );
        $author = get_sub_field( 'author' );
      ?>
        <div class="blockquote-block">
          <div class="row">
            <div class="img-block">
              <img src="<?php echo $image['url'] ?>" alt="<?php echo $image['alt'] ?>">
            </div>
            <blockquote>
              <p><?php echo $text; ?></p>
              <cite><?php echo $author; ?></cite>
            </blockquote>
          </div>
        </div>
      <?php endwhile; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if( !empty( get_field( 'sponsors_banners' ) ) ): ?>
<div class="ads-carousel">
  <?php 
    while( have_rows( 'sponsors_banners' ) ): the_row();
      $image = get_sub_field( 'image' );
      $slide_image = get_sub_field( 'slide_image' );
  ?>
    <div class="slide">
      <a href="#">
        <img src="images/ads01.jpg" height="98" width="673" alt="image description">
      </a>
    </div>
  <?php endwhile; ?>
</div>
<?php endif; ?>

<?php
  $slide = get_field( ‘slide’, get_the_ID() );
  if( !empty( $slide ) ):
?>
<div class="slideshow">
  <a href="#" class="btn-prev">prev</a>
  <a href="#" class="btn-next">next</a>
  <div class="mask">
    <div class="slideset">
      <?php while( have_rows('slide') ): the_row(); ?>
        <?php
          $slide_image = get_sub_field("slide_image", get_the_ID());
          $slide_title = get_sub_field("slide_title", get_the_ID());
          $slide_text = get_sub_field("slide_text", get_the_ID());
          $read_more_text = get_sub_field("read_more_text", get_the_ID());
          $read_more_link = get_sub_field("read_more_link", get_the_ID());
          
          if(empty($read_more_text)){ $read_more_text = 'Read More'; }
          if(empty($read_more_link)){ $read_more_link = '#'; }
          
          $slideimage = wp_get_attachment_image($slide_image['id'], 'slide-img');
        ?>
        <div class="slide">
          <?php if($slideimage): ?><div class="img"><?php echo $slideimage; ?></div><?php endif; ?>
          <div class="txt">
            <div class="text">
              <?php if($slide_title): ?><h1><?php echo $slide_title; ?></h1><?php endif; ?>
              <?php if($slide_text): ?><p><?php echo $slide_text; ?></p><?php endif; ?>
            </div>
            <div class="btn-holder">
              <div class="btn-frame">
                <a href="#" class="prev">Previous</a>
                <a href="<?php echo $read_more_link; ?>" class="btn-more"><?php echo $read_more_text; ?></a>
                <a href="#" class="next">Next</a>
              </div>
            </div>
          </div>
        </div>
      <?php endwhile; ?>
    </div>
  </div>
</div>
<?php endif; ?>

\!h acf flexible content Flexible Content flaxible

    <?php 
      $menu_section = get_field( 'menu_section' );
      if( $menu_section ):
    ?>
      <section class="menu-section" id="menu-section">
        <?php while( the_flexible_field( 'menu_section' ) ): ?>
                <?php if( get_row_layout() == "wide-closed-block" ): ?>
                    <div class="open-close skin line-holder js-anim-item">
              <div class="section-content">
                            <?php if( $title = get_sub_field( 'title' ) ): ?><h2 data-anim-class="fade-in"><a class="opener" href="#"><?php echo $title; ?></a></h2><?php endif; ?>
                            <?php if( $description = get_sub_field( 'description' ) ): ?><div class="slide"><div class="block"><?php echo $description; ?></div></div><?php endif; ?>
                        </div>
                    </div>
                <?php elseif(get_row_layout() == "wide-open-block"): ?>
                    <div class="block skin large-block line-holder js-anim-item">
              <div class="section-content">
                            <?php if( $title = get_sub_field( 'title' ) ): ?><h2 data-anim-class="fade-in"><?php echo $title; ?></h2><?php endif; ?>
                            <?php if( $description = get_sub_field( 'description' ) ): ?><?php echo $description; ?><?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endwhile; ?>
        </section>
      <?php endif; ?>

\!h acf social

<?php if( $footer_social_buttons ): ?>
  <ul class="social-networks">
      <?php
        while( have_rows( 'footer_social_buttons', 'option' ) ): the_row(); 
          $name = strtolower( get_sub_field( 'name' ) );
          $link = get_sub_field( 'link' );
      ?>
        <li><a href="<?php echo $link; ?>" target="_blank"><i class="icon-<?php echo $name; ?>"></i></a></li>
      <?php endwhile; ?>
  </ul>
<?php endif; ?>

<?php
    if( get_field( 'footer_social_buttons', 'option' ) ):
?>
    <div class="col-right">
        <?php if( $footer_social_title = get_field( 'footer_social_title', 'option' ) ): ?><strong class="sub-title"><?php echo $footer_social_title; ?></strong><?php endif; ?>
        <ul class="social-networks">
            <?php
                while( have_rows( 'footer_social_buttons', 'option' ) ): the_row(); 
                    $name = get_sub_field( 'name' );
                    $link = get_sub_field( 'link' );
            ?>
                <li><a href="<?php echo $link; ?>"><span class="icon <?php echo strtolower( str_replace( array( ' ', '+' ), array( '', '' ), $name ) ); ?>"></span><?php echo $name; ?></a></li>
            <?php endwhile; ?>
        </ul>
    </div>
<?php endif; ?>

<?php
          $facebook = get_field('facebook','option');
          $twitter = get_field('twitter','option');
          $flickr = get_field('flickr','option');
          $youtube = get_field('youtube','option');
          if($facebook || $twitter || $flickr || $youtube):
        ?>
          <ul class="social">
            <?php if($facebook): ?><li><a href="<?php echo $facebook; ?>">Facebook</a></li><?php endif; ?>
            <?php if($twitter): ?><li class="twitter"><a href="<?php echo $twitter; ?>">Twitter</a></li><?php endif; ?>
            <?php if($flickr): ?><li class="flickr"><a href="<?php echo $flickr; ?>">Flickr</a></li><?php endif; ?>
            <?php if($youtube): ?><li class="youtube"><a href="<?php echo $youtube; ?>">Youtube</a></li><?php endif; ?>
          </ul>
        <?php endif; ?>

\!h acf video file

<?php if( $hero_video ): ?>
  <video class="bg-video" width="640" height="360" loop autoplay muted playsinline>
    <source type="<?php echo $hero_video['mime_type'] ?>" src="<?php echo $hero_video['url'] ?>" />
  </video>
<?php endif; ?>
  
\!h acf related acf relationship relation

<?php 
  $posts = get_field('relationship_field_name');
  if( $posts ): 
?>
    <ul>
    <?php foreach( $posts as $post): ?>
        <?php setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <span>Custom field from $post: <?php the_field('author'); ?></span>
        </li>
    <?php endforeach; wp_reset_postdata(); ?>
    </ul>
<?php endif; ?>

\!h acf image

<?php
  $intro_image = get_field( 'intro_image' );
?>
<?php if ( $intro_image ): ?>
  <img src="<?php echo $intro_image['sizes']['thumbnail']; ?>" alt="<?php echo $intro_image['alt']; ?>" />
<?php endif; ?>

$galleryimage = wp_get_attachment_image($preview_gallery_image['id'], 'preview-gallery');

обновить поле с картинкой, нужен Field key, айди аттачмента

update_field('field_548f041013b5b', 2032, 'user_'.$current_user->ID);

\!h ----- acf gallery

<?php
  $gallery = get_field('gallery');
  if( $gallery ): 
?>
    <div class="gallery">
    <div class="mask">
        <div class="slideset">
              <?php foreach( $gallery as $image ): ?>
                <div class="slide"><img src="<?php echo $image['sizes']['1441x700']; ?>" alt="<?php echo $image['alt']; ?>" /></div>
              <?php endforeach; ?>
          </div>
        </div>
  </div>
  <div class="pagination"></div>
<?php endif; ?>

<?php
 
/*
*  View array data (for debugging)
*/
 
var_dump( get_field('gallery') );
 
/*
*  Create the Markup for a slider
*  This example will create the Markup for Flexslider (http://www.woothemes.com/flexslider/)
*/
 
$images = get_field('gallery');
 
if( $images ): ?>
    <div id="slider" class="flexslider">
        <ul class="slides">
            <?php foreach( $images as $image ): ?>
                <li>
                    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
                    <p><?php echo $image['caption']; ?></p>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php
 
    /*
    *  The following code creates the thumbnail navigation
    */
 
    ?>
    <div id="carousel" class="flexslider">
        <ul class="slides">
            <?php foreach( $images as $image ): ?>
                <li>
                    <img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; 
 
?>


\!h ----- google map acf google maps acf google map

include( get_template_directory() .'/GMapTool.php' );
<?php if( $location = get_field( 'map' ) ): $map_styles = get_field( 'map_styles' ); ?>
  <div class="map-section">
    <?php

      new GMapTool(array(
        'id' => 'google-map',
        'width' => '1425px',
        'height' => '456px',
        'zoom' => 16,
        'position' => $location,
        'default_icon' => $marker_image,
        'title' => $marker_title ? $marker_title : null,
        'popup' => $popup_content ? $popup_content : null,
        'styles' => $map_styles ? $map_styles : null,
      ));
    ?>
  </div>
<?php endif; ?>

/ ---- functions.php ----- /
add_action('wp_head', 'add_map_scripts');
function add_map_scripts(){
?>
 <style type="text/css">
  .map {
   width: 100%;
   height: 139px;
  }
 </style>
 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
 <script type="text/javascript">
  ;(function($){
   $(function(){
    $('.map').each(function(){
     var mapHolder = $(this),
      markers = mapHolder.find('.marker'),
      args = {
       zoom  : parseInt(mapHolder.attr('data-zoom')) || 9,
       center  : new google.maps.LatLng(0, 0),
       mapTypeId : google.maps.MapTypeId.ROADMAP
      },
      map = new google.maps.Map( mapHolder[0], args);
      
     function add_marker( marker, map ) {
      var latlng = new google.maps.LatLng( marker.attr('data-lat'), marker.attr('data-lng') ),
       newMarker = new google.maps.Marker({
        position : latlng,
        map   : map
       });
       
      // add to array
      map.markers.push( newMarker );
      
      // if marker contains HTML, add it to an infoWindow
      if( marker.html() ){
       // create info window
       var infowindow = new google.maps.InfoWindow({
        content  : marker.html()
       });
      
       // show info window when marker is clicked
       google.maps.event.addListener(newMarker, 'click', function() {
        infowindow.open( map, newMarker );
       });
      }
     }
     
     function center_map( map ) {
      var bounds = new google.maps.LatLngBounds();
      
      // loop through all markers and create bounds
      $.each( map.markers, function( i, marker ){
       var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
       bounds.extend( latlng );
      });
      
      // only 1 marker?
      if( map.markers.length == 1 ){
       // set center of map
       map.setCenter( bounds.getCenter() );
       map.setZoom( args.zoom );
      }
      else{
       // fit to bounds
       map.fitBounds( bounds );
      }
     }
      
     // add a markers reference
     map.markers = [];
     
     // add markers
     markers.each(function(){
      add_marker( $(this), map );
     });
     
     // center map
     center_map( map );
    });
   });
  }(jQuery));
 </script>
<?php
}

/ ----- page template ---- /

<?php
 $_map = get_field('map');
 
 if($_map):
?>
 <div class="map" data-zoom="14">
  <div class="marker" data-lat="<?php echo $_map['lat']; ?>" data-lng="<?php echo $_map['lng']; ?>">
   <?php echo $_map['address']; ?>
  </div>
 </div>
<?php endif; ?>

\!h ----- google map + GMApTools много маркеров

include( get_template_directory() .'/GMapTool.php' );

<?php 
            $map = new GMapTool();
            while( have_rows('destinations_sidebar') ): the_row(); 
          ?>
            <?php 
              $location = get_sub_field('map', get_the_ID());
              
              $map->addMarker(array(
                'position' => $location,
                'title' => $marker_title ? $marker_title : null,
                'popup' => $popup_content ? '‘ . $popup_content . ‘' : null,
                'icon' => $marker_image ? $marker_image : null,
              ));
            ?>
          <?php endwhile; ?>
          <?php
            $map->display(array(
              'id' => 'google-map',
              'center' => $location,
              'width' => '345px',
              'height' => '237px',
              'zoom' => 12,
              'type' => 'roadmap',
              'styles' => $styles ? $styles : null,
            ));
          ?>


—————— google map problems google maps problems acf google map —————————

Oops! Something went wrong.

создай апи
https://developers.google.com/maps/documentation/javascript/get-api-key#get-an-api-key

в functions.php 
function my_acf_init() {
    acf_update_setting('google_api_key', 'AIzaSyCfTa9jI5f64xKhkldhMx-lYKyM8_rEays');
}
add_action('acf/init', 'my_acf_init');

и там где подключается maps.googleapis.com если это GMapTool то правь прямо там
wp_enqueue_script('gmap-api', 'https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyCfTa9jI5f64xKhkldhMx-lYKyM8_rEays', array(), null, true);

—————————
<?php
/**
 * Create ACF setting page under Events CPT menu
 *
 * @since 1.0.0
 */
if ( function_exists( 'acf_add_options_sub_page' ) ){
  acf_add_options_sub_page(array(
    'title'      => 'Event Settings',
    'parent'     => 'edit.php?post_type=events',
    'capability' => 'manage_options'
  ));
}

\!h ----- acf кастомфилд хранит дату выборка постов по месяцам

function get_meta_key_values($meta_key){
  global $wpdb;
  if(empty($meta_key)){
   return FALSE;
  }
  return $wpdb->get_results($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = '%s' ORDER BY meta_value ASC", array($meta_key)));
}

\!h ----- ACF и таксономии

Как многие наверное знают в WP есть несколько багов связанных с таксономиями.
Например, выбранные таксономии всегда отображаются вверху списка чекбоксов независимо от установленного порядка, если таксономия не иерарахическая то есть проблемы и с сохраннием
Баги описаны в багтрекере но фиксить их пока не спешат)
ACF дает хорошую возможность решить часть проблем и отказаться от стандартного метабокса для таксономий.
Для этого нужно в настройках поля выбрать Save Terms и Load Terms что бы информация сохранялась не только в поле но и в параметрах термов и Create Tearms что бы можно было создавать новые термы прямо на странице.
https://s3.amazonaws.com/scrstorage/gul2a1023053e638w8.jpg
при регистрации таксономии указать 'meta_box_cb' => false что бы не выводить стандартный метабокс
 
Ну и конечно ACF дает возможность использовать все свои плюшки, если нужно отобразить таксономии в виде селекта, или связать отображение таксономии с выбранными термами другой тасономии