Wordpress acf when save post - php

When I save the post It create one post with correct value and an other with no title and no value!
add_filter('acf/pre_save_post' , 'tsm_do_pre_save_post' );
function tsm_do_pre_save_post( $post_id ) {
// Create a new post
$post = array(
'post_type' => 'itemfounds', // Your post type ( post, page, custom post type )
'post_status' => 'draft', // (publish, draft, private, etc.)
'post_title' => 'Δωρεά σε είδος για το "'.get_the_title(wp_strip_all_tags( $_POST['acf']['field_5696694332974'] )).'"' , // Post Title ACF field key
);
// insert the post
$post_id = wp_insert_post( $post );
session_start();
$_SESSION['item_pid'] = $post_id;
// Save the fields to the post
// do_action( 'acf/save_post' , $post_id );
return $post_id;
}

You can use acf by this way:-
$post_id (array) the ID of the post being saved
BEFORE
<?php
function my_acf_save_post( $post_id ) {
// bail early if no ACF data
if( empty($_POST['acf']) ) {
return;
}
// array of field values
$fields = $_POST['acf'];
// specific field value
$field = $_POST['acf']['field_abc123'];
}
// run before ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_post', 1);
?>
AFTER
<?php
function my_acf_save_post( $post_id ) {
// get new value
$value = get_field('my_field');
// do something
}
// run after ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_post', 20);
?>
Hope this will help you :)

Related

WordPress: Make first Image of ACF Gallery Field as featured Image with Frontend Post Submission

I am currently trying to use the first image of an ACF gallery field as featured image.
The plugin I use is called Frontend Admin, it allows users to create posts from the frontend.
While my script works in the WordPress backend, it does not work for the frontend submission:
add_action('acf/save_post', 'first_Image_featured', 50);
function first_Image_featured() {
//get important fields
$current_screen = get_current_screen(); // Current admin screen needed to identify the current cpt
$current_cpt_name = 'musterkueche'; // Current CPT name
$current_cpt_support = 'thumbnail'; // Check if the CPT supports this feature
global $post;
$post_id = ( $post->ID ); // Current post ID
$post_gallery_field = get_field('musterkuchengalerie', $post_id ); // ACF Image Gallery field
if ( !empty( $post_id ) ) {
if ( isset( $post_gallery_field['0'] ) ) {
$post_image_id = $post_gallery_field['0']['id']; // ACF image filed ID
$post_image_url = $post_gallery_field['0']['url']; // ACF image filed URL
// If current CPT supports thumbnails/featured images
if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
update_post_meta($post_id, '_thumbnail_id', $post_image_id);
}
}
} else {
update_post_meta( $post_id, '_thumbnail_id', 0 );
}
}
}
The Plugin Developer of Frontend Admin said:
Our frontend forms don't fire the acf/save_post hook, use do_action( 'frontend_admin/save_post', $form, $post_id ); instead.
$form (array) The form settings, including $form['record']['post'] which contains all of the submitted post fields’ data.
$post_id (int|string) The ID of the post being edited.
acf/save_post comparison for Frontend Admin
This hook is a bit different from acf/save_post so be aware of these differences:
$post_id is the second of two parameters, so make sure to include
both parameters and to set the fourth argument of add_action to “2”.
This hook is always fired after the fields have been saved so none of
the fields will be in the $_POST global but rather within the
$form['record']['fields'][‘post'] array.
Example Function for Frontend Admin (For sending email after post is saved)
add_action('frontend_admin/save_post', 'my_frontend_save_post', 10, 2);
function my_frontend_save_post( $form, $post_id ) {
//get important fields
$post_content = get_post_field('post_content',$post_id);
$post_title = get_post_field('post_title',$post_id);
$email_address = get_field('email_address', $post_id);
if( $email_address ) {
$email_sent = wp_mail( $email_address, $post_title, $post_content );
}
}
My second approach (dosent work):
add_action('frontend_admin/save_post', 'first_Image_featured', 10, 2);
function first_Image_featured ($form, $post_id) {
//get important fields
$current_screen = get_current_screen(); // Current admin screen needed to identify the current cpt
$current_cpt_name = get_post_type('musterkueche'); // Current cpt name
$current_cpt_support = 'thumbnail'; // Check if the CPT supports this feature
global $post; // This needs to be changed, but I dont understand the Documentation
$post_id = ( $post->ID ); // Current post ID
$post_gallery_field = get_field('musterkuchengalerie', $post_id); // ACF Image Gallery field
if ( !empty( $post_id ) ) {
if ( isset( $post_gallery_field['0'] ) ) {
$post_image_id = $post_gallery_field['0']['id']; // ACF image filed ID
$post_image_url = $post_gallery_field['0']['url']; // ACF image filed URL
// If current cpt supports thumbnails/featured images
if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
update_post_meta($post_id, '_thumbnail_id', $post_image_id);
}
}
} else {
update_post_meta( $post_id, '_thumbnail_id', 0 );
}
}
}

How to retrieve at Frontend the values of WordPress custom fields created for Media Library Images (Full example included)

I have 2 different working methods at functions.php for backend. Each method below has 2 hooks; 1 to display the new custom field & another hook to save\update the values:
Method 1:
function media_hacks_attachment_field_to_edit( $form_fields, $post ){
// https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
$media_author = get_post_meta( $post->ID, 'media_author', true );
$form_fields['media_author'] = array(
'value' => $media_author ? $media_author : '',
'label' => __( 'Author' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'media_hacks_attachment_field_to_edit', null, 2 );
//Saving value on Update (method 1)
function media_hacks_edit_attachment( $attachment_id ){
if ( isset( $_REQUEST['attachments'][$attachment_id]['media_author'] ) ) {
$media_author = $_REQUEST['attachments'][$attachment_id]['media_author'];
update_post_meta( $attachment_id, 'media_author', $media_author );
}
}
add_action( 'edit_attachment', 'media_hacks_edit_attachment' );
Method 2:
function my_image_attachment_fields_to_edit($form_fields, $post) {
// $form_fields is a special array of fields to include in the attachment form
// $post is the attachment record in the database
// $post->post_type == 'attachment'
// (attachments are treated as posts in Wordpress)
// add our custom field to the $form_fields array
// input type="text" name/id="attachments[$attachment->ID][custom1]"
$form_fields["custom1"] = array(
"label" => __("Custom Text Field"),
"input" => "text", // this is default if "input" is omitted
"value" => get_post_meta($post->ID, "_custom1", true)
);
// if you will be adding error messages for your field,
// then in order to not overwrite them, as they are pre-attached
// to this array, you would need to set the field up like this:
$form_fields["custom1"]["label"] = __("Custom Text Field");
$form_fields["custom1"]["input"] = "text";
$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);
return $form_fields;
}
// attach our function to the correct hook
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);
//Saving value on Update (method 2)
function my_image_attachment_fields_to_save($post, $attachment) {
// $attachment part of the form $_POST ($_POST[attachments][postID])
// $post attachments wp post array - will be saved after returned
// $post['post_type'] == 'attachment'
if( isset($attachment['custom1']) ){
// update_post_meta(postID, meta_key, meta_value);
update_post_meta($post['ID'], '_custom1', $attachment['custom1']);
}
return $post;
}
add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null, 2);
Here's the good result at backend Media Library (Custom Text Field & Author):
This was it for the Backend dashboard.
My question is for the Frontend:
Now how can I retrieve & display values of these 2 custom fields at the FRONTEND?
Here's my failed try at a template php page:
<tr id='MySpecialRow'>
<td colspan='2' style='background:#000;color:#fff;'>
<?php
$args = array('cat' => 8);
$query = new WP_Query($args);
if ($query->have_posts()) {
// some code here if you want.
while ($query->have_posts()) {
$query->the_post();
$untitled_meta = rwmb_meta('image_advanced_8hswqfsoqai', '', get_the_ID());
foreach ($untitled_meta as $image) {
$media_author = get_post_meta( get_the_ID(), 'media_author', true );
echo get_the_ID();//correctly prints post id
echo $media_author;//prints nothing :(
}
}
}
?>
</td>
</tr>
Small notes:
get_the_ID() does print the post id, but $media_author has no value :(
I'm doing a WordPress posts query loop because the gallery containing the custom fields exists in a Post. In other words I don't have the post Id since I'm at a Page template.
The array you got has the image post object ID as the array keys, so you need to use the extended foreach syntax to get access to the key as well.
foreach ($untitled_meta as $id => $image) {
$media_author = get_post_meta( $id, 'media_author', true );
Normally when looping over array data you rather seldom need access to the key as well, but when you do, PHP offers the $key => $value syntax to get access to the key as well, https://www.php.net/manual/en/control-structures.foreach.php

Change post permalink dynamically via custom field on save/update

I'm wanting to change a WordPress post's permalink (post_name) dynamically every time time a post is saved/updated by pulling from a custom field present in the post and replacing the permalink with this value. I have code within functions.php which is working, except that it appends -2 to the permalink. I assume this is because something is occurring twice, the first time resulting in the permalink I want, and the second resulting in WordPress responding to the "duplicate" by adding -2.
This is the current code:
add_action('save_post', 'change_default_slug');
function change_default_slug($post_id) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
if ( !current_user_can('edit_post', $post_id) )
return;
remove_action('save_post', 'change_default_slug');
wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'request_number',true)));;
add_action('save_post', 'change_default_slug');
}
I'll take a crack at this...
Now, this is assuming that you are using ACF for your custom field...
If not, simply update the code with the WP custom meta functions instead. Oh, don't forget the change the field_5fed2cdbc1fd2 with your ACF field Key
add_filter('save_post', 'change_post_name', 20, 1);
function change_post_name($post_id)
{
$post_type = get_post_type();
if ($post_type == "post"){
$acf_title_field = $_POST['acf']['field_5fed2cdbc1fd2']; // get the field data by $_POST
if (!empty($acf_title_field)) {
// update the title in database
$wpdb->update($wpdb->posts, array('post_title' => $acf_title_field, 'post_name' => sanitize_title($acf_title_field)), array('ID' => $post_id));
}
}
}
add_filter( 'wp_insert_post_data', 'update_post_name', 50, 2 );
function update_post_name( $data, $postarr ) {
$post_type = get_post_type();
if ($post_type == "post"){
//Check for the post statuses you want to avoid
if ( !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
$acf_title_field = $_POST['acf']['field_5fed2cdbc1fd2']; // get the field data by $_POST
// $data['post_name'] = sanitize_title( $data['post_title'] );
$data['post_name'] = sanitize_title( $acf_title_field );
}
return $data;
}
}

How to set custom post type field as post title to avoid 'Auto Draft'

I am using the Advanced custom fields plugin and Custom post type UI to give my users some extra functionality. The problem I have is that I have setup a users information menu and in the list view all new posts appear as Auto Draft. Is there anyway I can make the field slug company name act as the post title for the list view?.
I tried the below code but it is not updating the company name as post title and in the custom post page it display message like "You are currently editing the page that shows your latest posts."
My Sample code:
add_filter('title_save_pre', 'save_title');
function save_title() {
if ($_POST['post_type'] == 'users') : // my custom post type name
$new_title = $_POST['company_name']; // my custom field name
$my_post_title = $new_title;
endif;
return $my_post_title;
}
Use name="post_title" in your input.
<input type="text" name="post_title" id="meta-text" class="form-control" value="">
this should work:
add_action( 'acf/save_post', 'save_post_handler' , 20 );
function save_post_handler( $post_id ) {
if ( get_post_type( $post_id ) == 'users' ) {
$title = get_field( 'company_name', $post_id );
$data['post_title'] = $title;
$data['post_name'] = sanitize_title( $title );
wp_update_post( $data );
}
}
disclaimer: I literally just read the php website top to bottom yesterday, but I read a few posts about trying to do this and assembled this solution that is working for me. I have a custom post type called artists, I combine the artist acf field of first_name and last_name and set that as the title. For your example you could remove the parts that add last name.
// Auto-populate artist post type title with ACF first name last name.
function nd_update_postdata( $value, $post_id, $field ) {
// If this isn't an 'artists' post type, don't update it.
if ( get_post_type( $post_id ) == 'artists' ) {
$first_name = get_field('first_name', $post_id);
$last_name = get_field('last_name', $post_id);
$title = $first_name . ' ' . $last_name;
$slug = sanitize_title( $title );
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'artists',
'post_name' => $slug
);
wp_update_post( $postdata, true );
return $value;
}
}
add_filter('acf/update_value/name=first_name', 'nd_update_postdata',
10, 3);
add_filter('acf/update_value/name=last_name', 'nd_update_postdata', 10,
3);

Wordpress front end posting to multiple blog in multisite with advanced custom field

I am using advanced custom field frond end posting.
<?php
function my_pre_save_post( $post_id )
{
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_status' => 'draft' ,
'post_title' => 'A title, maybe a $_POST variable' ,
'post_type' => 'post' ,
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
?>
I want to use this method
<?php
$original_blog_id = get_current_blog_id(); // get current blog
$bids = array(1,2); // all the blog_id's to loop through
foreach($bids as $bid):
switch_to_blog($bid); //switched to blog with blog_id $bid
// ... your code for each blog ...
endforeach ;
switch_to_blog( $original_blog_id ); //switched back to current blog
?>
How can I Post to multiple blog at same time. please help me.
Problem Solved!. I got a solution from here.
http://support.advancedcustomfields.com/forums/topic/front-end-posting-to-multiple-blog/

Categories