John, thanks for the add_attachment
tip.
I also found similar code at https://wordpress.stackexchange.com/a/310689/39300
Whilst it assumes Post is the connected object, it also works for User.
The following code now takes the connected User’s name and uses that also for Title and Alt fields.
All told, now I have:
Thanks!
/**
* ==============================================================================
* ALSO SET IMAGE TITLE & ALT TO USER/POST NAME
* When an image is uploaded, use the attached Post (User) edtails
* to set Title, Alt fields etc.
* cf. https://wordpress.stackexchange.com/a/310689/39300
* cf. https://support.advancedcustomfields.com/forums/topic/force-an-image-file-upload-to-a-particular-directory/page/2/
* ==============================================================================
*/
// https://wordpress.stackexchange.com/a/310689/39300
function my_set_image_meta_upon_image_upload( $post_ID ) {
// "the first thing that your action should do is to remove
// itself so that it does not run again."
remove_filter('add_attachment', 'your_function_name_here');
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$my_image_title = get_post( $post_ID )->post_title;
// Added by Robert Andrews
// Get user name to use in image details
$user = get_user_by( 'slug', $my_image_title );
$user_name = $user->display_name;
$my_image_title = $user_name;
// Sanitize the title: remove hyphens, underscores & extra spaces:
// $my_image_title = preg_replace( '%[-_]+%', ' ', $my_image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
// $my_image_title = ucwords( strtolower( $my_image_title ) );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
// 'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
// 'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', 'Photo of '.$my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
Hi @pbalazs89
You could run 2 queries.
The first loop you would query by the custom field ‘featured’ and set the posts per page to 2
You then add another loop but this time query by the next custom field.
Would that work for you?
This is what worked for me. Based on @hube2 but cleaned up a bit. Thanks!
<a href="<?php the_sub_field('link', 'option'); ?>" target="_blank">
<img class="test" src="<?php the_sub_field('image'); ?>" alt="<?php
echo get_post_meta(get_sub_field('image', false), '_wp_attachment_image_alt', true); ?>">
</a>
It is actually relatively simple.I would like to create and evaluate a yearly catch list of all members for the fishing club.
There are different waters, different fish species from the amount of fish weight is calculated.
So this all works with repaeter.
look here https://isen-fischer.de/form/fangmeldung-gaeste/
I can also create post of it and see them in a list view.
Now would like to process the data further.
in Goggle sheet, I can not read the repeater. Only completely as text. But no single repeater.
With DB query I don’t know my way around.
this is my problem.
gr Wolfgang
Hi @flexi2202,
Is your form only visible to logged in users? I assume you’re logged in as non-admin?
I think you need to use the acf_form() parameters
On of the parameters is: html_after_fields.
As you’re logged in, you can access the user ID:
$user_id = get_current_user_id();
So you could then use a hidden value:
'html_after_fields' => '<input type="hidden" name="acf[author_id]" value="'.$user_id.'"/>',
Using acf/save_post
You can then grab the hidden value and updated the post author:
add_action('acf/save_post', 'my_acf_save_post');
function my_acf_save_post( $post_id ) {
$arg = array(
'ID' => $post_id,
'post_author' => $_POST['acf']['author_id']
);
wp_update_post( $arg );
}
Code is untested but should point you in the right direction
Do any of your price ranges only have 2?
If you add a wp_reset_query(); after before the closing for each, does that make a difference?
No, I was talking about your options for calling acf_form(). Yours are wrong.
$options = array(
'post_id' => 'new',
'field_groups' => array(
4
),
'post_title' => true,
'new_post' => array(
'post_type' => 'recette',
'post_status' => 'draft',
),
'updated_message' => __("Recette publiée", 'acf'),
'submit_value' => 'Postez votre recette'
);
acf_form($options);
I think it’s the query in the foreach.
What if you change it to:
$args = array(
'posts_per_page' => -1,
'post_type' => 'your post type',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'price',
'value' => $price,
'compare' => '<='
),
)
);
Specify the post type and see if that works?
We know the data up to that point is right, so the issue is that query. Just need to tweak it
Ah, think we need one minor amend, please try:
<?php
$args = array(
'post_type' => 'cars',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'post_type' => 'cars',
'post_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'sold',
'value' => array('no'),
'compare' => 'IN',
),
)
)
);
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) :
$get_price = array();
while ($wp_query->have_posts()) : $wp_query->the_post();
$get_price[] = get_field('price');
endwhile;
endif; #endif $wp_query
echo '<pre>';
print_r($get_price);
echo '</pre>';
$filter_price = array_unique($get_price);
echo '<pre>';
print_r($filter_price);
echo '</pre>';
if($filter_price):
foreach($filter_price as $price):
echo '<p>Price: '.$price.'</p>';
$args = array(
'key' => 'price',
'value' => $price,
'type' => 'numeric',
'compare' => '<=',
);
$wp_query = new WP_Query($args);
$figure_total = $wp_query->found_posts;
$count = count( $wp_query->get_posts() );
echo '<p>$figure_total: '.$figure_total.' count: '.$count.'</p>';
endforeach;
endif; #endif $filter_price
I think we need count not found
Try adding some debugging to the code, see what outputs you get at the various stages:
<?php
$args = array(
'post_type' => 'cars',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'post_type' => 'cars',
'post_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'sold',
'value' => array('no'),
'compare' => 'IN',
),
)
)
);
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) :
$get_price = array();
while ($wp_query->have_posts()) : $wp_query->the_post();
$get_price[] = get_field('price');
endwhile;
endif; #endif $wp_query
echo '<pre>';
print_r($get_price);
echo '</pre>';
$filter_price = array_unique($get_price);
echo '<pre>';
print_r($filter_price);
echo '</pre>';
if($filter_price):
foreach($filter_price as $price):
echo '<p>Price: '.$price.'</p>';
$args = array(
'key' => 'price',
'value' => $price,
'type' => 'numeric',
'compare' => '<=',
);
$wp_query = new WP_Query($args);
$figure_total = $wp_query->found_posts;
echo $figure_total;
endforeach;
endif; #endif $filter_price
So first thing is see what the main array gets
Then see what the filtered results returns
When you then loop the filtered array, output the values as a heading
I did just adjust the query in the foreach, as mentioned, I’ve not tested the code, just trying to cobble it together as a starting point.
Absolutely no idea if this would work or not:
<?php
$args = array(
'post_type' => 'cars',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'post_type' => 'cars',
'post_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'sold',
'value' => array('no'),
'compare' => 'IN',
),
)
)
);
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) :
$get_price = array();
while ($wp_query->have_posts()) : $wp_query->the_post();
$get_price[] = get_field('price');
endwhile;
endif; #endif $wp_query
$filter_price = array_unique($get_price);
if($filter_price):
foreach($filter_price as $price):
$figure = new WP_Query(
$args,
array(
'key' => 'price',
'value' => $price,
'type' => 'numeric',
'compare' => '<=',
)
);
$query = new WP_Query( $figure );
$figure_total = $query->found_posts;
echo $figure_total;
endforeach;
endif; #endif $filter_price
Basically, you loop all the individual prices and put them into an array
Filter the prices to remove duplicates
Then loop the filtered results and pass the value into your query
Your query then returns the count
Not tried the code!
There are plugins that allow saving data to a different DB table, but there is nothing available that will work with repeaters.
How to use a repeater https://www.advancedcustomfields.com/resources/repeater/
Importing data requires a plugin that will work with ACF fields. One example is WP All Import Pro.
Thank you jarvis and John Huebner,
in my case I prefer the jarvis’s solution because directly in template file I can apply the both query quickly!
https://drive.google.com/file/d/1nQlxM8UZVU3uGwjZlRFlqnwmZoAUO4oC/view?usp=sharing
The answer by @jarvis is a good solution. There is another option that is slightly more complicated. You can use an acf/fields/relationship/query filter.
Somewhere in your functions.php file add
function acf_relationship_only_struttura($args) {
$args['post_type'] = 'struttura';
return $args;
}
Then just in your template where you want to show the field
add_filter('acf/fields/relationship/query/name=relazioni_strutture', 'acf_relationship_only_struttura');
$posts = get_field('relazioni_strutture');
remove_filter('acf/fields/relationship/query/name=relazioni_strutture', 'acf_relationship_only_struttura');
There is not mechanism in WP that will allow you to query posts based on the meta values of a related post. To query posts all values must be associated with the posts you want to query.
This means that you need to
– create an acf/save_post hook that
– gets the relationship field
– gets the values for the fields on the related post
– saves those values to the post currently being saved
Hi @atise
If you’re creating an image field, when you add the code to your template (please see here), you can add the class to your img tag.
Once you add the class, say ‘responsive-img’, you can then reference that in your CSS.
So:
<?php
$image = get_field('image');
if( !empty( $image ) ): ?>
<img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>" class="responsive-img" />
<?php endif; ?>
Then in your CSS:
.responsive-img {
/*whatever you need to add*/
}
Hi @liqid
Ok, so hardcoding works, which means it must be when outputting the field that additional code(?) is being added.
If you hard code it and it works, copy the line into something like notepad
Then, add your code back in, inspect it and copy the line into notepad
If you compare them, does the latter one have anything different? If so, what is the difference?
Hi @pmmg
I think I’d be inclined to do something like:
$current_url = get_permalink();
$state_url = get_field('state_url');
$product = get_title();
echo '<a href="$current_url.$state_url.'-'.$product">Link</a>';
Or
$site_url = get_site_url();
$state_url = get_field('state_url');
$product = get_title();
echo '<a href="$site_url.'/product/'.$state_url.'-'.$product">Link</a>';
May need a little tweaking but should get you underway!
Hi @avahidesign
I guess you can approach it in different ways.
If you’re looping through your CPT, you can simply echo out the custom field if it exists:
<?php
global $wp_query;
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 10,
'post_type' => 'your-cpt',
'paged' => $paged
);
$wp_query = new WP_Query($args); ?>
<?php if ($wp_query->have_posts()) : ?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post();
$position = get_field('position');
?>
Your loop content
<?php
if($position):
echo $position;
endif;
?>
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>
Or you can add ACF fields to a custom excerpt:
// Custom Excerpt function for Advanced Custom Fields
function custom_field_excerpt() {
global $post;
$text = get_field('position'); //Replace 'your_field_name'
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = 20; // 20 words
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
return apply_filters('the_excerpt', $text);
}
Then in your loop, display the custom excerpt:
echo custom_field_excerpt();
Hi @liqid,
What does ‘social_icon_static’ return?
If you hard code that line (so do away with the get_field part), does it still display outside the tag? If not, then it’s how the include is working.
I’m sure I had similar once before with something. If you declare the get_field above, then include the $var, does that work:
if ( $depth == 0 ) {
$social_icon_static = get_field('social_icon_static', $item);
$item_output .= '<div class="uk-inline-clip uk-transition-toggle uk-animation-toggle social-icon-container" tabindex="0">
<svg class="uk-animation-slide-top uk-animation-reverse social-top" width="16px" height="16px"> '. get_template_part( 'assets/images/svg/inline', $social_icon_static) .' </svg>
<svg class="uk-transition-slide-bottom social-bottom" width="16px" height="16px"> '. get_template_part( 'assets/images/svg/inline', get_field('social_icon_hover', $item)) .' </svg>
</div>';
}
If hard coding still blows it out, then it must be non ACF related. Sometimes, using the browser inspect tool can help as you can play about with it, then adjust the code accordingly.
Hi @unbekannter
The below will output the selected checkboxes into an array:
$values = array();
$time = get_field('second-field');
foreach ($time as $second) {
$values[] = '"'.$second.'" => 0';
}
echo implode(',', $values);
Do you need it as an associative array? I’m trying to work out it out.
You asked for checkboxes to be an array but the example you give of how it needs to be is more like an associative array (I believe but could be wrong!).
Judging from the way Adam Balée’s code augments the SQL query, it appears that the term names are already in the post meta table. Here are the two PHP statements in his code that modify the query (they are in separate functions, but clearly end up in the same piece of SQL):
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
I’ve done something similar with Gravity forms, whereby someone would submit content and I needed to use the added image field to set the featured image on the new post.
The code used this:
$upload_path = rgar($entry, '11');
if (!empty($upload_path)){
$attachmentid = wp_create_image_id($upload_path, $member_post_id);
$setfeatimg = set_post_thumbnail($member_post_id, $attachmentid);
}
Obviously, you would need to alter from a gravity form field to your.
$member_post_id was the post ID I needed to add the image to
function wp_create_image_id( $image_url, $parent_post_id = null ) {
// Bail if the image url isn't valid
if( empty( $image_url ) || ! esc_url( $image_url ) )
return false;
// Escape the url, just to be save
$image_url = esc_url( $image_url );
// Cache info on the wp uploads dir
$wp_upload_dir = wp_upload_dir();
// get the file path
$path = parse_url( $image_url, PHP_URL_PATH );
// File base name, e.g. image.jpg
$file_base_name = basename( $image_url );
// Full path, set up to work with a WP in a subdirectory or default location
if( site_url() != home_url() ) {
$home_path = dirname( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) );
} else {
$home_path = dirname( dirname( dirname( dirname( __FILE__ ) ) ) );
}
// Remove the trailing slash on the home path
$home_path = untrailingslashit( $home_path );
// Combine the two to get the uploaded file path
$uploaded_file_path = $home_path . $path;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( $file_base_name, null );
// error check
if( !empty( $filetype ) && is_array( $filetype ) ) {
// Create attachment title - basically, pull out the text
$post_title = preg_replace( '/\.[^.]+$/', '', $file_base_name );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $uploaded_file_path ),
'post_mime_type' => $filetype['type'],
'post_title' => esc_attr( $post_title ),
'post_content' => '',
'post_status' => 'inherit'
);
// Set the post parent id if there is one
if( ! is_null( $parent_post_id ) && absint( $parent_post_id ) )
$attachment['post_parent'] = absint( $parent_post_id );
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $uploaded_file_path );
//Error check
if( !is_wp_error( $attach_id ) ) {
//Generate wp attachment meta data
if( file_exists( ABSPATH . 'wp-admin/includes/image.php') && file_exists( ABSPATH . 'wp-admin/includes/media.php') ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
} // end if file exists check
} // end if error check
return $attach_id;
} else {
return false;
} // end if $filetype
} // end function prg_create_image_id
If you need to get the image path, please read this forum post
Hi @miksynder
You would need to query your posts to see if your custom field exists, something like:
<?php
$args = array(
'post_type' => array('post', 'page'),
'posts_per_page' => 10,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'start_date',
'compare' => 'EXISTS',
),
),
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<h2>Amazing Events List</h2>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $start_date = get_field('start_date');?>
<li>
<a href="<?php the_permalink(); ?>">
<?php if($start_date): echo $start_date; endif; ?>
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
The featured image for a post is stored as a post ID (attachment ID), this means that it is an image in the media library and this is required. In order to do this you would need to download and insert the image into media. see media_sideload_image()
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.