Support

Account

Home Forums Search Search Results for '%s'

Search Results for '%s'

reply

  • What code do you have?

    Maybe I’ve misunderstood.

    This loops categories:

    <?php
    $categories = get_categories( array(
        'orderby' => 'name',
        'order'   => 'ASC'
    ) );
     
    foreach( $categories as $category ) {
        $category_link = sprintf( 
            '<a href="%1$s" alt="%2$s">%3$s</a>',
            esc_url( get_category_link( $category->term_id ) ),
            esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
            esc_html( $category->name )
        );
         
        echo '<p>' . sprintf( esc_html__( 'Category: %s', 'textdomain' ), $category_link ) . '</p> ';
        echo '<p>' . sprintf( esc_html__( 'Description: %s', 'textdomain' ), $category->description ) . '</p>';
        echo '<p>' . sprintf( esc_html__( 'Post Count: %s', 'textdomain' ), $category->count ) . '</p>';
    } 

    This loops taxonomies:

    <?php if( $categories = get_terms( array( 'taxonomy' => 'floor4' ) ) ) :
    foreach( $categories as $cat) : 
    	$hover= get_field('hover', 'term_' .$cat->term_id  );?>
    	<?php echo $hover; ?>
    <?php endforeach;      
    endif;
    ?>
  • I’ll share the solution with you.
    I just understood that in the acf_form () function; you had to pass all the form tags.
    Whose input action
    Here is the script that works to adapt of course to your needs:

    /*====Shortcode contenu News Tab  - ACF  ================= */
    
    add_action( 'admin_post_adaptiveweb_save_profile_form', 'adaptiveweb_save_profile_form' );
    function adaptiveweb_save_profile_form() {
      if(!isset($_REQUEST['user_id'])) return;
    
      do_action('acf/save_post', $_REQUEST['user_id']);
    
      wp_redirect(add_query_arg('updated', 'success', wp_get_referer()));
      exit;
    }
    
    /* Contenu ACF dans Shortcode */
    
    function contenu_shortcode_onglet( $atts ) {
    
    $user_ID = get_current_user_id();
    $user = wp_get_current_user();
    
    $options = array(
        // 'field_groups' => ['group_618a52d0b2b74'],
        
        'fields' => [
            'field_618a52d0b874e',
            'field_618a52d0b878d',
            'field_618a52d0b87ce',
            'field_618a52d0b880f',
            'field_618a52d0b870d',
            'field_618a526a02cd7',
            'field_618a526a02d0f'
    
        ],
    
        'form_attributes' => [
            'method' => 'POST',
            'action' => admin_url("admin-post.php"),
        ],
    
        'html_before_fields' => sprintf(
            '<input type="hidden" name="action" value="adaptiveweb_save_profile_form">
            <input type="hidden" name="user_id" value="user_%s">', $user->ID
        ),
    
        'post_id' => "user_{$user->ID}",
        'form' => true,
        'html_submit_button' => '<button type="submit" class="acf-button button" value="Update Profile">Update Profile</button>',
        'updated_message' => __('<div class="woocommerce-message" role="alert">
            Les détails du compte ont bien été modifiés.</div>', 'acf')
        
    );
    
    acf_form($options);
    
    }
    add_shortcode( 'onglet', 'contenu_shortcode_onglet' );
  • Okay, using this code

    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
      <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
        <div class="splide__track">
            <ul class="post-grid splide__list">
                <?php 
                if( $molecules_of_the_month = get_terms( array( 'taxonomy' => 'molecules_of_the_month', $args ) ) ) :
                    foreach( $molecules_of_the_month as $month ) : 
                        $summaryimage  = get_field('summary_preview_image', 'term_' .$month->term_id  ); // field, id and format value
                        // $summaryimage = get_field('summary_preview_image', 'term_name_', 'molecules_of_the_month'); // NULL++
                        $size = 'full'; // (thumbnail, medium, large, full or custom size)
                        // var_dump($summaryimage);
                        echo '<a href="' . esc_url( get_term_link( $month ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'drughunter' ), $month->name) ) . '">' 
                        . $month->name . '</a>';
                    endforeach;
                endif; ?>
            </ul>
        </div>
      </div>
    </div>

    I have the summaryimage loading ids but not in use yet as I need image url. This so I can load the image, title and short description and link it all.

    I also can still load term links using this loop and an echo so that is fine. But need to work out loading image first.

    Furthermore I need to include the $args I had before. Not sure how with current setup. Doing some trials still.

  • @jarvis I used your code with foreach loops:

    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
            <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
                <div class="splide__track">
                    <ul class="post-grid splide__list">
                        <?php 
                        if( $molecules_of_the_month = get_terms( array( 'taxonomy' => 'molecules_of_the_month' ) ) ) :
                            foreach( $molecules_of_the_month as $month ) : 
                                $summaryimage  = get_field('summary_preview_image', 'term_' .$month->term_id  );
                                $size = 'full'; // (thumbnail, medium, large, full or custom size)
                                print_r($summaryimage);
                                // $molecules_of_the_month .= '<a href="' . esc_url( get_term_link( $month ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'theme' ), 
                                // $month->name ) ) . '">' . $month->name . '</a><figure class="post-featured-image">' . 
                                // wp_get_attachment_image( $summaryimage, $size ) . '</figure>';
                            endforeach;
                        endif; ?>
                    </ul>
                </div>
            </div>
        </div>

    and I know get 328235043514 or this using var_dump

    NULL int(3282) bool(false) bool(false) bool(false) int(3504) int(3514) bool(false) NULL bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false)

    so I am getting something now. So I guess I needed to load the image in the foreach loop. But I also see you used:

    <?php $summaryimage = get_field('summary_preview_image', 'term_' .$month->term_id );?>

    with term_ .$month->term_id which I am clearly not familiar enough with. Besides understanding this better I also need to load the image url so guess I do not want ID numbers only. How would I do that?

    NB had to post this 3 times to make it stick on the forum

  • @jarvis I used your code with foreach loops:

    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
            <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
                <div class="splide__track">
                    <ul class="post-grid splide__list">
                        <?php 
                        if( $molecules_of_the_month = get_terms( array( 'taxonomy' => 'molecules_of_the_month' ) ) ) :
                            foreach( $molecules_of_the_month as $month ) : 
                                $summaryimage  = get_field('summary_preview_image', 'term_' .$month->term_id  );
                                $size = 'full'; // (thumbnail, medium, large, full or custom size)
                                print_r($summaryimage);
                                // $molecules_of_the_month .= '<a href="' . esc_url( get_term_link( $month ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'theme' ), 
                                // $month->name ) ) . '">' . $month->name . '</a><figure class="post-featured-image">' . 
                                // wp_get_attachment_image( $summaryimage, $size ) . '</figure>';
                            endforeach;
                        endif; ?>
                    </ul>
                </div>
            </div>
        </div>

    and I know get 328235043514 or this using var_dump

    NULL int(3282) bool(false) bool(false) bool(false) int(3504) int(3514) bool(false) NULL bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false)

    so I am getting something now. So I guess I needed to load the image in the foreach loop. But I also see you used:

    <?php $summaryimage = get_field('summary_preview_image', 'term_' .$month->term_id );?>

    with term_ .$month->term_id which I am clearly not familiar enough with. Besides understanding this better I also need to load the image url so guess I do not want ID numbers only. How would I do that?

  • I tried

    <?php $args = array( 'hide_empty=0', 
                    'childless'     => 1, 
                    'number'        => 6,
                    'orderby'       => 'ID', 
                    'order'         => 'ASC'
                    ); 
    
    $terms = get_terms( 'molecules_of_the_month', $args );
    if ( ! empty( $terms )   ) :
        // $termid = get_queried_object()->term_id;
        // var_dump($termid);
        $summaryimage = get_field('summary_preview_image', 'tax_name_', 'molecules_of_the_month');
        // print_r($summaryimage);
        $size = 'full'; // (thumbnail, medium, large, full or custom size)
        $count = count( $terms );
        $i = 0;
        $term_list = '<p class="molecule-of-the-month">';
        ?>
        <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
            <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
                <div class="splide__track">
                    <ul class="post-grid splide__list">
                        <?php 
                        if($term_list):
                            foreach ( $terms as $term ) {
                                $i++;
                                $term_list .= '<a href="' . esc_url( get_term_link( $term ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'theme' ), 
                                $term->name ) ) . '">' . $term->name . '</a><figure class="post-featured-image">' . 
                                wp_get_attachment_image( $summaryimage, $size )
                                . '</figure>';
                                
                                if ( $count != $i ) {
                                    $term_list .= ' &middot; ';
                                }
                                else {
                                    $term_list .= '</p>';
                                }
                            }
                            echo $term_list;
    
                        endif; ?>
                    </ul>
                </div>
            </div>
        </div>
    <?php endif;?>

    and the var_dump for summary_image is NULL. Do not get it. And the ACF field is there:

    if( function_exists('acf_add_local_field_group') ):
    
    acf_add_local_field_group(array(
    	'key' => 'group_612651d5d04ad',
    	'title' => 'Molecule Archive Fields',
    	'fields' => array(
    		array(
    			'key' => 'field_6126521430c38',
    			'label' => 'Slide Deck',
    			'name' => 'slide_deck',
    			'type' => 'file',
    			'instructions' => '',
    			'required' => 0,
    			'conditional_logic' => 0,
    			'wrapper' => array(
    				'width' => '',
    				'class' => '',
    				'id' => '',
    			),
    			'return_format' => 'array',
    			'library' => 'all',
    			'min_size' => '',
    			'max_size' => '',
    			'mime_types' => '',
    		),
    		array(
    			'key' => 'field_6126525730c39',
    			'label' => 'Slide Deck Preview Image',
    			'name' => 'preview_image',
    			'type' => 'image',
    			'instructions' => '',
    			'required' => 0,
    			'conditional_logic' => 0,
    			'wrapper' => array(
    				'width' => '',
    				'class' => '',
    				'id' => '',
    			),
    			'return_format' => 'id',
    			'preview_size' => 'medium',
    			'library' => 'all',
    			'min_width' => '',
    			'min_height' => '',
    			'min_size' => '',
    			'max_width' => '',
    			'max_height' => '',
    			'max_size' => '',
    			'mime_types' => '',
    		),
    		array(
    			'key' => 'field_6131b9c9bedc9',
    			'label' => 'Summary',
    			'name' => 'summary',
    			'type' => 'file',
    			'instructions' => '',
    			'required' => 0,
    			'conditional_logic' => 0,
    			'wrapper' => array(
    				'width' => '',
    				'class' => '',
    				'id' => '',
    			),
    			'return_format' => 'array',
    			'library' => 'all',
    			'min_size' => '',
    			'max_size' => '',
    			'mime_types' => '',
    		),
    		array(
    			'key' => 'field_6131b9e1bedca',
    			'label' => 'Summary Preview Image',
    			'name' => 'summary_preview_image',
    			'type' => 'image',
    			'instructions' => '',
    			'required' => 0,
    			'conditional_logic' => 0,
    			'wrapper' => array(
    				'width' => '',
    				'class' => '',
    				'id' => '',
    			),
    			'return_format' => 'id',
    			'preview_size' => 'medium',
    			'library' => 'all',
    			'min_width' => '',
    			'min_height' => '',
    			'min_size' => '',
    			'max_width' => '',
    			'max_height' => '',
    			'max_size' => '',
    			'mime_types' => '',
    		),
    	),
    	'location' => array(
    		array(
    			array(
    				'param' => 'taxonomy',
    				'operator' => '==',
    				'value' => 'molecules_of_the_month',
    			),
    		),
    		array(
    			array(
    				'param' => 'taxonomy',
    				'operator' => '==',
    				'value' => 'molecules_of_the_year',
    			),
    		),
    	),
    	'menu_order' => 0,
    	'position' => 'normal',
    	'style' => 'default',
    	'label_placement' => 'top',
    	'instruction_placement' => 'label',
    	'hide_on_screen' => '',
    	'active' => true,
    	'description' => '',
    ));
    
    endif;
  • Hi @peternitras-be

    If you look at the docs for a gallery field, it may help.

    If you need to use a shortcode, here’s how the code should look:

    <?php
    
    // Load value (array of ids).
    $image_ids = get_field('gallery');
    if( $image_ids ) {
    
        // Generate string of ids ("123,456,789").
        $images_string = implode( ',', $image_ids );
    
        // Generate and do shortcode.
        // Note: The following string is split to simply prevent our own website from rendering the gallery shortcode.
        $shortcode = sprintf( '[' . 'gallery ids="%s"]', esc_attr($images_string) );
        echo do_shortcode( $shortcode );
    }
  • You will need to adapt the following to match your fields etc:

    <?php
    				$args 						= array(
    					'post_type'				=> 'stockist',
    					'order'					=> 'ASC',
    					'order_by'				=> 'title',
    					'posts_per_page'		=> -1,
    				);
    
    				$query = new WP_Query( $args );
    				if ( $query->have_posts() ) :
    
    					while ( $query->have_posts() ) : $query->the_post();
    						$the_id				= get_the_ID();
    						$location 			= get_field( 'company_address' );
    						$link				= get_field( 'company_link' );
    						$phone 				= get_field( 'company_phone' );
    						$country 			= get_field( 'country_name' );
    						$logo 				= get_field( 'company_logo' );
    						$size 				= 'productsml';
    
    						if ( ! empty( $location ) ) {
    				?>
    							<div class="acf-map">
    								<div class="marker text-center" data-lat="<?php echo esc_attr( $location['lat'] ); ?>" data-lng="<?php echo esc_attr( $location['lng'] ); ?>">
    									<?php
    									if ( $logo ) {
    										echo wp_get_attachment_image( $logo, $size );
    									}
    									?>
    									<h3><?php the_title(); ?></h3>
    
    									<?php
    									if ( $location ) {
    										$address 	= '';
    										foreach ( array( 'street_number', 'street_name', 'city', 'state', 'post_code', 'country' ) as $i => $k ) {
    											if ( isset( $location[ $k ] ) ) {
    												$address .= sprintf( '<span class="segment-%s">%s<br /></span>, ', $k, $location[ $k ] );
    											}
    										}
    											$address = trim( $address, ', ' );
    									?>
    											<p><?php echo esc_html( $location['address'] ); ?></p>
    									<?php
    									}
    									?>
    
    									<?php if ( $phone ) { ?>
    										<p><?php echo esc_attr( $phone ); ?> </p>
    									<?php } ?>
    
    									<?php if ( $link ) { ?>
    										<a class="button" href="<?php echo esc_url( $link ); ?>">Visit Website </a>
    									<?php } ?>
    
    							</div>
    				<?php
    						}
    					endwhile;
    				endif;
    				?>
  • I know this is an old post, but you can grab the field label from the ‘posts’ table.

      if (!function_exists('getAcfLabelByName')) {
    
        function getAcfLabelByName($fieldName = null) {
    
            if (empty($fieldName)) {
                return 'No field name specified';
            }
    
            // set a default in case there's an exception
    
            $fieldLabel = 'Not Found';
    
            try {
    
                /**
                 * ACF stores the the Labels in the
                 * wp_posts table, where the ACF label is the title
                 * and the excerpt is the field name
                 */
    
                global $wpdb;
    
                $tableName = "{$wpdb->prefix}posts";
    
                $labelReturned = $wpdb->get_var( $wpdb->prepare( "SELECT post_title FROM $tableName 
                WHERE post_type = %s AND post_excerpt = %s", 'acf-field', $fieldName ));
    
                // grab the post_title from the result
    
                $fieldLabel = !empty($labelReturned) ? $labelReturned : 'Not Found';
                
    
            } catch (Exception $e) {
                
                $error = $e->getMessage();
    
                error_log("There was an exception finding the ACF field label by name with the message $error");
    
                
            }
    
            return $fieldLabel;
    
        }
    
      }

    You can then use this like:

    $fieldLabel = getAcfLabelByName('field_name_here');

    For what it’s worth I created a simple plugin to add this function to your site:

    https://wordpress.org/plugins/get-acf-field-label-from-name/

  • I had a similar issue where i needed to add the ACF fields meta_id. Below is my solution to the same problem

    function build_meta_key($field){
        // Loop over parents.
        $return_name = $field["_name"];
    
        if(empty($field["prefix"])){
            return $return_name;
        }
    
        $is_row = preg_match("/row-(\d)+/", $field["prefix"], $matches);
    
        if(!$is_row){
            return $return_name;
        }
    
        //now figure out the row number from the field name
    
        $return_name = $matches[1]."_".$return_name;
        
        while ( $field['parent'] && $field = acf_get_field( $field['parent'] ) ) {
            if(isset($field["_name"])){
                $return_name = $field["_name"]."_".$return_name;
            }
        }
    
        return $return_name;
    }
    
    function get_all_meta_info_by_key($post_id,  $meta_key, $meta_type = "post"){
    	global $wpdb;
    	if ( ! $meta_type || ! $post_id || trim($meta_key) == "") {
    		return false;
    	}
    
    	$table = _get_meta_table( $meta_type );
    	if ( ! $table ) {
    		return false;
    	}
    
    	$meta = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$table} WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key) );
    
    	if ( empty( $meta ) ) {
    		return false;
    	}
    
    	if ( isset( $meta->meta_value ) ) {
    		$meta->meta_value = maybe_unserialize( $meta->meta_value );
    	}
    
    	return $meta;
    }
    
    /**
     * Add in the ACF fields meta id to the field itself. so we can build the download links
     * @param $field
     *
     * @return mixed
     */
    function prepare_field( $field ) {
        global $post;
    
        $acf_meta_key = $this->build_meta_key($field);
    
        $meta_information = $this->get_all_meta_info_by_key($post->ID,  $acf_meta_key);
    
        if(!empty($meta_information->meta_id)){
            $field["post_meta_id"] = $meta_information->meta_id;
        }
    
        return $field;
    }
  • I’m pasting a note from original solution:

    Given answer has potential to give false positives.

    E.g. you’re after posts with IDs 528 and 76, but there are also posts with IDs 5287, 4528, 765 and 2769 which you don’t intent to get, but they might happen to match the rest of the query.

    The same is true to any values, since matching “apple” will give you false positive on “apple_pie” or “applejuice” etc.

    Internally arrays are serialized and look like

    
    a:4:{i:0;s:3:"528";i:1;s:5:"15289";i:2;s:5:"apple";i:3;s:9:"apple_pie";}
    

    note double quotes around values – which you can use to make sure that you’re matching exactly what you want

    To safely query for values in them, just include quotation around value you’re after:

    
    $meta_query[] = array(
        'key'     => 'checkbox',
        'value'   => sprintf('"%s"', $item),
        'compare' => 'LIKE',
    );
    

    You can also add colon before and semicolon after to explicitly telegraph your intention to query serialized value:

    
    'value'   => sprintf(':"%s";', $item),
    
  • Given answer has potential to give false positives.

    E.g. you’re after posts with IDs 528 and 76, but there are also posts with IDs 5287, 4528, 765 and 2769 which you don’t intent to get, but they might happen to match the rest of the query.

    The same is true to any values, since matching “apple” will give you false positive on “apple_pie” or “applejuice” etc.

    Internally arrays are serialized and look like

    
    a:4:{i:0;s:3:"528";i:1;s:5:"15289";i:2;s:5:"apple";i:3;s:9:"apple_pie";}
    

    note double quotes around values – which you can use to make sure that you’re matching exactly what you want

    To safely query for values in them, just include quotation around value you’re after:

    
    $meta_query[] = array(
        'key'     => 'checkbox',
        'value'   => sprintf('"%s"', $item),
        'compare' => 'LIKE',
    );
    

    You can also add colon before and semicolon after to explicitly telegraph your intention to query serialized value:

    
    'value'   => sprintf(':"%s";', $item),
    
  • Hi plugin author, I had implemented ACF PRO latest version in the website,

    I have created a flexible content for section and implemented background color and background image for each section,

    As per my design , i have created my design almost complete but when the client says to add something above certain section the issue is showing. At first I create a section through flexible content and reorder as per the client needs the background image is showing in two section one with background color and one with background image itself

    I had created a dummy page for the issue to show you in my website.

    Page Link

    I have also included some pics of the issue.

    Here is my code

    At page.php file I run a flexible content loop and set the content to desired templates as need.

    `<?php
    //Get subfield values
    $section_background = get_sub_field(‘section_background’);

    $section_color = get_sub_field(‘section_background_color’);

    $section_extra_class = get_sub_field(‘section_extra_classes’);

    ?>

    <?php if (!empty($section_background)): ?>
    <?php $unique_id = esc_attr(uniqid(‘section-‘));?>
    <style>
    #<?php echo $unique_id; ?> {
    background-image: url(<?php echo $section_background; ?>);
    }
    </style>
    <?php endif;?>

    <section class=”section<?php echo sprintf(‘ %s %s’, $section_color, $section_extra_class); ?>” <?php if (isset($unique_id)) {
    echo sprintf(‘ id=”%s”‘, $unique_id); }?>>

    <div class=”container”>
    <?php
    /**
    * Loop through layout types registered in ACF plugin.
    * Field group -> “Page Sections” -> “Section” -> “Section Content Types”
    *
    */
    if (have_rows(‘section_content_types’)):
    while (have_rows(‘section_content_types’)): the_row();

    //Regular Layout
    if (get_row_layout() == ‘regular_layout’):

    get_template_part(‘template-parts/page/layout’, ‘regular’);

    //Equal Columns Layout
    elseif (get_row_layout() == ‘equal_column_layout’):

    get_template_part(‘template-parts/page/layout’, ‘equal-columns’);

    //Landing Layout
    elseif (get_row_layout() == ‘landing_layout’):

    get_template_part(‘template-parts/page/layout’, ‘landing’);

    //Tabs Layout
    elseif (get_row_layout() == ‘tabs_layout’):

    get_template_part(‘template-parts/page/layout’, ‘tabs’);

    endif;

    endwhile;
    endif;
    ?>
    </div>
    </section>

    ACF In posts

    ACF Structure in Posts

    When the New Section is added

    When New Section is added

    When Reordering The section

    When Reordering the section

    In Inspect Element

    In Inspect Element

    here is my issue in Problem.

  • I’ve been tinkering and finally found something that works:

    
    		<form method="get" action="" onchange="submit();">
    			<div class="input-group">
    				<?php
    				global $wpdb;
    				$meta_key = 'item_oem';
    				$data = $wpdb->get_results($wpdb->prepare( "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key) , ARRAY_N  ); ?>
    				<select class="custom-select" id="oems" aria-label="oems" name="item_oem" >
    					<option selected>Search By OEM</option>
    					<?php foreach( $data as $value ): ?>
    						<option value="<?php echo $value[0]; ?>"><?php echo $value[0]; ?> </option>
    					<?php endforeach; ?>
    			  </select>
    			  <div class="input-group-append">
    			    <a href="/inventory" class="btn btn-secondary" type="button">Clear Filter</a>
    			  </div>
    			</div>
    		</form>
    
    

    I’ll definitely look through your suggestions as well, and see which one works the best.. I don’t want to take a hit on performance just for a filter 🙂

    Thank you!

  • Hello,
    thank you for your reply.

    Hm i have added it before (forgot to have it on the code i gave to the topic) but nothing happened. I tested again with the code below but nothing works.

    <?php 
     
    acf_form_head();
    get_header();
    ?>
    <div class="container">
    <?php
      $settings = array(
        'id' => 'photos_form',
        'post_id' => 'new_post',
        'new_post' => ['post_type' => 'photos', 'post_status' => 'draft'],
        'field_groups' => array("group_6025117548b3f"),
        'fields' => false,
        'submit_value' => __("Submit", 'acf'),
        'label_placement' => 'top',
        'html_submit_button' => '<input type="submit" id="submitbtn" class="acf-button button primary_btn" value="%s" />',
        'html_submit_spinner' => '<span class="acf-spinner"></span>',
        'updated_message' => '',
        'html_after_fields' => '',
    );
    acf_form($settings);?>
    </div>
    <?php get_footer(); ?>

    Is there any mistake in that code? Didn’t understand something in the correct way?

    Thank you again.
    George

  • You need to add the post_id and new_post param to the $settings array.
    Plz replace ‘your-cpt’ with the name of your custom post type.

    $settings = array(
        'id' => 'photos_form',
        'post_id' => 'new_post',
        'new_post' => [
            'post_type' => 'your-cpt',
            'post_status' => 'draft',
         ],
        'field_groups' => array("group_6025117548b3f"),
        'fields' => false,
        'submit_value' => __("Submit", 'acf'),
        'label_placement' => 'top',
        'html_submit_button' => '<input type="submit" id="submitbtn" class="acf-button button primary_btn" value="%s" />',
        'html_submit_spinner' => '<span class="acf-spinner"></span>',
        'updated_message' => '',
        'html_after_fields' => '',
    );
  • Hi John! Thank you for your response! It was the function “acf_get_all_field_keys”. It’s a custom function which gets the field-keys (field_123456) from the database. Here is the code:

    function acf_get_all_field_key( $meta_key ) {
    	global $wpdb;
    	$acf_fields = $wpdb->get_results( $wpdb->prepare( "
    		SELECT 'meta_value'
    		FROM '$wpdb->postmeta'
    		WHERE 'post_id' = 3077 
    		AND 'meta_key'
    		LIKE %s",
    		$meta_key
    		)
    		);
    	// get all fields with that name.
    	switch ( count( $acf_fields ) ) {
    		case 0: // no such field
    			return false;
    		case 1: // just one result. 
    			return $acf_fields[0]->meta_value;
    		default:
    			return array ($acf_fields);
    	}
    }

    I changed the post-id for this function to a fix ID of a published event, so it’s always returning values.

    I founded this function here: https://gist.github.com/mcguffin/81509c36a4a28d9c682e

    Thank you for your help! This topic is solved.

  • I’m doing something similar and using this DB call. This is using the Haversine formula.

      
    
    global $wpdb;
      $tablePrefix = $wpdb->prefix;
      $query = $wpdb->prepare("SELECT ".$tablePrefix."posts.*,
      a.meta_value street_address,
      b.meta_value city,
      c.meta_value state,
      d.meta_value zip_code,
      e.meta_value phone,
      f.meta_value website,
      g.meta_value latitude,
      h.meta_value longitude,
      ( 3959 * acos( cos( radians('%s') ) * cos( radians( g.meta_value ) ) * cos( radians( h.meta_value ) - radians(%s) ) + sin( radians('%s') ) * sin( radians( g.meta_value ) ) ) ) AS distance
      FROM ".$tablePrefix."posts
      LEFT JOIN ".$tablePrefix."postmeta a ON ".$tablePrefix."posts.ID = a.post_ID AND a.meta_key='street_address'
      LEFT JOIN ".$tablePrefix."postmeta b ON ".$tablePrefix."posts.ID = b.post_ID AND b.meta_key='city'
      LEFT JOIN ".$tablePrefix."postmeta c ON ".$tablePrefix."posts.ID = c.post_ID AND c.meta_key='state'
      LEFT JOIN ".$tablePrefix."postmeta d ON ".$tablePrefix."posts.ID = d.post_ID AND d.meta_key='zip_code'
      LEFT JOIN ".$tablePrefix."postmeta e ON ".$tablePrefix."posts.ID = e.post_ID AND e.meta_key='phone'
      LEFT JOIN ".$tablePrefix."postmeta f ON ".$tablePrefix."posts.ID = f.post_ID AND f.meta_key='website'
      LEFT JOIN ".$tablePrefix."postmeta g ON ".$tablePrefix."posts.ID = g.post_ID AND g.meta_key='latitude'
      LEFT JOIN ".$tablePrefix."postmeta h ON ".$tablePrefix."posts.ID = h.post_ID AND h.meta_key='longitude'
      WHERE ".$tablePrefix."posts.post_type = 'acf-store' AND ".$tablePrefix."posts.post_status = 'publish'
      HAVING distance < '%s'
      ORDER BY distance LIMIT 0 , 100",
                  $center_lat,
                  $center_lng,
                  $center_lat,
                  $radius);
    
         $store_data = $wpdb->get_results($query);
    
  • 
    $products = get_field('products_in_this_auction', false false);
    $categories = get_terms('type_produc', 'orderby=count&order=DESC&hide_empty=1');
                          foreach( $categories as $category ): 
                          ?>
                          <h3 class="title_pru"><?php echo $category->name; // Prints the cat/taxonomy group title ?></h3>
                          <?php
                          $posts = get_posts(array(
    'post__in' => $products,
                          'post_type' => 'myproduct',
                          'taxonomy' => $category->taxonomy,
                          'term' => $category->slug,
                          'nopaging' => true,
                          ));
                          foreach($posts as $post): 
                          setup_postdata($post); 
                          ?>
                         
                          <div id="post-<?php the_ID(); ?>">
                         
                        
                        <?php  the_title( sprintf( '<p class="title_pru"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></p>' ); ?>
                         
                       
                         
                          </div><!-- #post-## --> 
                          <?php endforeach; ?>
                         
                         <?php endforeach; ?>
    
  • Nevermind found a fix myself 🙂

    I think the main reason was related to the fact that the “return format” was set to “Image URL” instead of “Image Array”.

    After I changed that in my WordPress backend I now use the following code in my template and it gives me the alt tag and title tag of the image:

    <?php 
    $image = get_sub_field('inside_the_customer_imgs'); 
    printf( '<img src="%s" alt="%s" title="%s" />', $image['url'], $image['alt'], $image['title'] );         
    ?>
  • Hi,
    Thank you very much for your help.
    I have been able to solve a large part of the problem.
    Thank you very much for responding so promptly.

    Order Custom Post Type by Taxonomy-OK

    The only problem with this solution is that WordPress shows me Taxonomies that have posts from other auctions.

    While WordPress does not show empty taxonomies thanks to the ‘hide_empty’ rule hide_empty => true , it does show taxonomies that have a custom post type but belong to another auction.

    Do you have any idea what I should change in the code below so that it only shows the taxonomies that are associated with the products of this auction?

    Greetings and thank you very much for your help.

    My code:

         $products = get_field('products_in_this_auction', false, false);      
                          $categories = get_terms( 'type_produc', array(
                            'orderby' =>   'count',
                            'order'=>'DESC',                        
                            'hide_empty' => true
                        ) );
                         
                         
                          foreach( $categories as $category ): 
                           
                          ?>
                          <h3 class="title_pru"><?php echo  $category->name;  ?></h3>
                          <?php
                        $query = get_posts(array(
                            'post__in' => $products,
                            'post_type' => 'myproduct',
                            'taxonomy' => $category->taxonomy,
                            'term' => $category->slug,
                            'nopaging' => true,
                            ));
                          foreach($query as $post): 
                          setup_postdata($post); 
                          ?>
                         
                          <div id="post-<?php the_ID(); ?>">
                         
                        
                        <?php  the_title( sprintf( '<p class="title_pru"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></p>' ); ?>
                         
                       
                         
                          </div><!-- #post-## --> 
                          <?php endforeach; ?>
                         
                         <?php endforeach; ?>
  • 
    add_filter( 'parse_query', 'ba_admin_posts_filter' );
    add_action( 'restrict_manage_posts', 'ba_admin_posts_filter_restrict_manage_posts' );
    
    function ba_admin_posts_filter( $query )
    {
        global $pagenow;
        if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && $_GET['ADMIN_FILTER_FIELD_NAME'] != '') {
            $query->query_vars['meta_key'] = $_GET['ADMIN_FILTER_FIELD_NAME'];
        if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '')
            $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
        }
    }
    
    function ba_admin_posts_filter_restrict_manage_posts()
    {
    $fields = array(
      'field_1',
      'field_2',
      'field_3',
      'field_4',
      'etc...'
    );
    ?>
    <select name="ADMIN_FILTER_FIELD_NAME">
    <option value=""><?php _e('Filter By Custom Fields', 'baapf'); ?></option>
    <?php
        $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
        $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
        foreach ($fields as $field) {
    	printf('<option value="%s"%s>%s</option>', $field, $field == $current? ' selected="selected"':'', $field);
    }
    ?>
    </select> <?php _e('Value:', 'baapf'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
    <?php
    }
    
  • Hi John

    thanks for the reply.

    so my code bellow how it will be after adding the codes you have in your reply?

    could you please reply with the full code as per you early reply.

    
    
    add_filter( 'parse_query', 'ba_admin_posts_filter' );
    add_action( 'restrict_manage_posts', 'ba_admin_posts_filter_restrict_manage_posts' );
    
    function ba_admin_posts_filter( $query )
    {
        global $pagenow;
        if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && $_GET['ADMIN_FILTER_FIELD_NAME'] != '') {
            $query->query_vars['meta_key'] = $_GET['ADMIN_FILTER_FIELD_NAME'];
        if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '')
            $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
        }
    }
    
    function ba_admin_posts_filter_restrict_manage_posts()
    {
        global $wpdb;
        $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
        $fields = $wpdb->get_results($sql, ARRAY_N);
    ?>
    <select name="ADMIN_FILTER_FIELD_NAME">
    <option value=""><?php _e('Filter By Custom Fields', 'baapf'); ?></option>
    <?php
        $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
        $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
        foreach ($fields as $field) {
            if (substr($field[0],0,1) != "_"){
            printf
                (
                    '<option value="%s"%s>%s</option>',
                    $field[0],
                    $field[0] == $current? ' selected="selected"':'',
                    $field[0]
                );
            }
        }
    ?>
    </select> <?php _e('Value:', 'baapf'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
    <?php
    }
    
  • Instead of doing the query to get a list of all avialble fields, construct an array with the field that you want to search.

    
    $fields = array(
      'field_1',
      'field_2',
      'field_3',
      'field_4',
      'etc...'
    );
    

    then alter the code used to display the field to use this new array

    
    foreach ($fields as $field) {
    	printf('<option value="%s"%s>%s</option>', $field, $field == $current? ' selected="selected"':'', $field);
    }
    
  • Solution

    I should’ve known there would be a built in solution for this. First time I’ve used a filter on the relationship field results, but this is so, so useful.

    For anyone else who comes across this, here’s a helpful tutorial just to bring it all home: https://philkurth.com.au/tips/customise-the-post-titles-in-acf-relationship-field/

    Here’s how I adapted it to show me a bit more info about the returned results and still make it reasonably legible:

      add_filter( 'acf/fields/relationship/result', function ( $title, WP_Post $post, $field_arr ) {
    
        $posted_at = get_post_time( 'U', false, $post->ID );
        $now = current_time( 'timestamp' );
        $diff = human_time_diff( $posted_at, $now );
        $permalink = get_permalink( $post->ID );
    
        return '<strong>' . $title . '</strong><br>' . $permalink . sprintf( ' (%s ago)', $diff );
      }, 10, 3 );

    This outputs the permalink of each page, along with how long ago it was published. Combined with the small featured image this should be enough to recognise any page.

    Just one more reason to love this plugin.

Viewing 25 results - 51 through 75 (of 180 total)