Change post thumbnail on using front end post edit form [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm trying to get the post thumbnail to change if a user selects a new file on a front end post edit screen. This is similar to the code I use to upload data and set the post thumbnail on a front end add new post form:
<?php
$query = new WP_Query( array( 'post_type' => 'properties', 'posts_per_page' => '-1' ) );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
if(isset($_GET['post'])) {
if($_GET['post'] == $post->ID)
{
$current_post = $post->ID;
$content = get_the_content();
$price = get_post_meta($post->ID, 'shru_price', true);
$address = get_post_meta($post->ID, 'shru_address', true);
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-image' );
}
}
endwhile; endif;
wp_reset_query();
global $current_post;
$postContentError = '';
if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {
if ( trim( $_POST['postContent'] ) === '' ) {
$postContentError = 'Please enter a description of this property.';
$hasError = true;
}
$post_information = array(
'ID' => $current_post,
'post_content' => $_POST['postContent'],
'post_type' => 'properties',
'post_status' => 'publish'
);
$post_id = wp_update_post($post_information);
function upload_user_file( $file = array() ) {
global $post_id;
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'], $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
$propertyfor = $_POST['propertyfor'];
$propertytype = $_POST['propertytype'];
$bedrooms = $_POST['bedrooms'];
if($post_id) {
// Update Custom Meta
update_post_meta($post_id, 'shru_price', esc_attr(strip_tags($_POST['shru_price'])));
update_post_meta($post_id, 'shru_address', esc_attr(strip_tags($_POST['shru_address'])));
update_post_meta($post_id, '_thumbnail_id', $attachment_id );
wp_set_object_terms( $post_id, $propertyfor, 'propertyfor' );
wp_set_object_terms( $post_id, $propertytype, 'propertytype' );
wp_set_object_terms( $post_id, $bedrooms, 'bedrooms' );
// Redirect
wp_redirect(home_url('/listings'));
exit;
}
}
?>
The only difference is that in the code above I am trying to use:
update_post_meta($post_id, '_thumbnail_id', $attachment_id );
instead of:
set_post_thumbnail($post_id, $attachment_id);
For some reason, on the post edit screen the image file does not even upload. When I use update post meta, it removes the old thumbnail, so I guess it's doing it's job there, but since the file isn't uploading it cannot replace it with a new one. The confusion is why the file uploads using the upload_user_file function on the add new post screen but not the edit post screen.
Any ideas?

Related

Find the Function that saves the image of product variation-WooCommerce

I'm trying to update the function that handles the upload of the image to variation product
![image variation] https://i.imgur.com/reNn6x7.png
I thought that the code that handles it is :
protected function set_variation_image( $variation, $image ) {
$attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0;
if ( 0 === $attachment_id && isset( $image['src'] ) ) {
$upload = wc_rest_upload_image_from_url( esc_url_raw( $image['src'] ) );
if ( is_wp_error( $upload ) ) {
if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $variation->get_id(), array( $image ) ) ) {
throw new WC_REST_Exception( 'woocommerce_variation_image_upload_error', $upload->get_error_message(), 400 );
}
}
$attachment_id = wc_rest_set_uploaded_image_as_attachment( $upload, $variation->get_id() );
}
if ( ! wp_attachment_is_image( $attachment_id ) ) {
/* translators: %s: attachment ID */
throw new WC_REST_Exception( 'woocommerce_variation_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 );
}
$variation->set_image_id( $attachment_id );
// Set the image alt if present.
if ( ! empty( $image['alt'] ) ) {
update_post_meta( $attachment_id, '_wp_attachment_image_alt', wc_clean( $image['alt'] ) );
}
// Set the image name if present.
if ( ! empty( $image['name'] ) ) {
wp_update_post(
array(
'ID' => $attachment_id,
'post_title' => $image['name'],
)
);
}
return $variation;
} `
inside the class-wc-rest-product-variations-controller.php
but any modification at this function is not changing the way that the file is uploaded.
the idea is to upload the image and apply the same variation image to each variation available, but can't find the function that saves the image to the product.
#edit after itzmekhokan reply
i created a plugin that add action to woocommerce_save_product_variation
add_action('woocommerce_save_product_variation', 'salvarfoto',10,2);
function salvarfoto($variation_id,$i){
$variation = new WC_Product_Variation($variation_id);
$produto_pai =wc_get_product( $variation->get_parent_id() );
foreach( $produto_pai->get_children() as $variation_values ){
// $variation_id = $variation_values['variation_id']; // variation id
$product = new WC_Product_Variation( $variation_values );
if( $product->get_attribute( 'pa_cor' ) == $variation->get_attribute('pa_cor'))
{
$id_img = $variation->get_image_id();
$product->set_image_id($id_img);
}
$product->save();
}
}
this code apply the same image_id to all variations that has the same color attribute
Its WC_Meta_Box_Product_Data::save_variations( $post_id, $post ) within file class-wc-meta-box-product-data.php.
And -
$errors = $variation->set_props(
array(
'image_id' => isset( $_POST['upload_image_id'][ $i ] ) ? wc_clean( wp_unslash( $_POST['upload_image_id'][ $i ] ) ) : null,
)
);
image_id basically storing the each variation image id. Check the functionalities first, then I think you can do your modifications using this do_action( 'woocommerce_save_product_variation', $variation_id, $i ); hook.

add "duplicate" to custom post type admin menu

I'm trying to add the "duplicate" post option to my custom post type admin menu called events. I have searched online, but there is very little documentation on how to add this function to the custom post types. Perhaps I am using the incorrect terminology when searching.
The code below adds the "duplicate" function, but when clicked it doesn't actually duplicate the post but returns a white screen instead. Are there any pointers or tips that you can give me?
function rd_duplicate_post_link( $actions, $post ) {
if (current_user_can('edit_posts') || $post->post_type=='events') {
$actions['duplicate'] = 'Duplicate';
}
return $actions;
}
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2)
You need to call admin_action_rd_duplicate_post_as_draft hook
function rd_duplicate_post_link( $actions, $post ) {
//print_r($actions);
//if (current_user_can('edit_posts') || $post->post_type=='movies') {
$actions['duplicate'] = 'Duplicate';
// }
return $actions;
}
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
add_action( 'admin_action_rd_duplicate_post_as_draft', 'dt_dpp_post_as_draft' );
function dt_dpp_post_as_draft()
{
global $wpdb;
/*sanitize_GET POST REQUEST*/
$post_copy = sanitize_text_field( $_POST["post"] );
$get_copy = sanitize_text_field( $_GET['post'] );
$request_copy = sanitize_text_field( $_REQUEST['action'] );
$opt = get_option('dpp_wpp_page_options');
$suffix = !empty($opt['dpp_post_suffix']) ? ' -- '.$opt['dpp_post_suffix'] : '';
$post_status = !empty($opt['dpp_post_status']) ? $opt['dpp_post_status'] : 'draft';
$redirectit = !empty($opt['dpp_post_redirect']) ? $opt['dpp_post_redirect'] : 'to_list';
if (! ( isset( $get_copy ) || isset( $post_copy ) || ( isset($request_copy) && 'dt_dpp_post_as_draft' == $request_copy ) ) ) {
wp_die('No post!');
}
$returnpage = '';
/* Get post id */
$post_id = (isset($get_copy) ? $get_copy : $post_copy );
$post = get_post( $post_id );
$current_user = wp_get_current_user();
$new_post_author = $current_user->ID;
/*Create the post Copy */
if (isset( $post ) && $post != null) {
/* Post data array */
$args = array('comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $new_post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => $post_status,
'post_title' => $post->post_title.$suffix,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
$new_post_id = wp_insert_post( $args );
$taxonomies = get_object_taxonomies($post->post_type);
if(!empty($taxonomies) && is_array($taxonomies)):
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);}
endif;
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
$meta_value = addslashes($meta_info->meta_value);
$sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'";
}
$sql_query.= implode(" UNION ALL ", $sql_query_sel);
$wpdb->query($sql_query);
}
/*choice redirect */
if($post->post_type != 'post'):$returnpage = '?post_type='.$post->post_type; endif;
if(!empty($redirectit) && $redirectit == 'to_list'):wp_redirect( admin_url( 'edit.php'.$returnpage ) );
elseif(!empty($redirectit) && $redirectit == 'to_page'):wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
else:
wp_redirect( admin_url( 'edit.php'.$returnpage ) );
endif;
exit;
} else {
wp_die('Error! Post creation failed: ' . $post_id);
}
}

WordPress: Convert comments to Posts when approved

I'm using the function below to convert WP-comments to WP-posts. I want it to be fired when "approving" a comment. (now it is whenever the plug-in is activated in WP).
So really I'm wondering how to ad my function to this action from line 47 of the edit-comments.php:
foreach ( $comment_ids as $comment_id ) { // Check the permissions on each
if ( !current_user_can( 'edit_comment', $comment_id ) )
continue;
switch ( $doaction ) {
case 'approve' :
wp_set_comment_status( $comment_id, 'approve' );
$approved++;
break;
[...]
}
}
Plug-in function:
register_activation_hook( __FILE__, 'convert_to_posts' );
function convert_to_posts(){
$comments = get_comments();
foreach($comments as $comment)
{
$post = get_post($comment->comment_post_ID);
$title = get_comment_meta( $comment->comment_ID, 'title', true );
$content = $comment->comment_content;
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1
);
wp_insert_post( $my_post );
// wp_delete_comment( $comment->comment_ID );
}
}

WordPress theme not pulling through title text of images

I am trying to make the theme I am using (DICE) into pulling through title text of images.
The code I am using is below;
if ( has_post_thumbnail() ) {
if ( $linking == 'lightbox' ) {
$alt = esc_attr(get_the_title( $post->ID ) );
$the_title = esc_attr(get_the_title( $post->ID ) );
$img = get_the_post_thumbnail( $post->ID, $size, array( 'alt' => $alt, 'title' => $the_title ) );
}
else
$img = get_the_post_thumbnail( $post->ID, $size );
}
elseif( $placeholder ) {
$img = btp_render_placeholder( $size, '', false );
}
else {
return;
}
The only line I have added is
$the_title = esc_attr(get_the_title( $post->ID ) );
with
'title' => $the_title
in the array aswell. The alt text is pulling through fine, so I'm unsure as to why the title text isn't pulling through?
Any help is appreciated. Thanks.
Using two separate variables to get the same information is bad programming practice.
Try to use only one variable, like this:
if ( $linking == 'lightbox' ) {
$post_title = esc_attr(get_the_title( $post->ID ) );
//The Image
$img = get_the_post_thumbnail( $post->ID, $size, array( 'alt' => $post_title, 'title' => $post_title ) );
}

how to upload an image on ACF with update_field on wordpress

I have a form, which has an upload ($_FILES['watch_photo']) field.
I have looked around and came to put this function together.
It basically takes all relevant information so it is re-usable in the future, it will return an array of the $pid, and URL of the file, when it is done.
The problem is that ACF has not provided much information how to add images to it's fields using update_field() http://www.advancedcustomfields.com/resources/functions/update_field/
function my_update_attachment($f,$pid,$t='',$c='') {
wp_update_attachment_metadata( $pid, $f );
if( !empty( $_FILES[$f]['name'] )) { //New upload
require_once( ABSPATH . 'wp-admin/includes/file.php' );
$override['action'] = 'editpost';
$file = wp_handle_upload( $_FILES[$f], $override );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($_FILES[$f]['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
return array(
'pid' =>$pid,
'url' =>$file['url']
);
// update_post_meta( $pid, 'a_image', $file['url'] );
}
}
}
and then I used the following code:
to create a post and then
upload then use my_update_attachment to process the image
and finally update the advanced custom field
The code:
$args= array( 'post_type' => 'watches', 'post_status' => 'publish' );
$watch = wp_insert_post($args);
$att = my_update_attachment('watch_image',$watch);
update_field('field_512e085a9372a',$att['url'],$watch);
What am I missing? any help would be greatly appreciated.
I had the same problem, you almost had it right, which helped me as well.
looked at ACF and the update_field accepts attachment ID as oppose to the the, pid or url
You can replace the return array:
return array(
'pid' =>$pid,
'url' =>$file['url']
);
With the following array:
return array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
and then change
update_field('field_512e085a9372a',$att['url'],$watch);
with the following
update_field('field_512e085a9372a',$att['attach_id'],$watch);
should this line
if ( !is_wp_error( $id )) {
be
if ( !is_wp_error( $attach_id )) {
Check this plugin:
https://wordpress.org/plugins/acf-frontend-display/
Create ACF form with frontendUploader field (plugin extention)
Add your ACF form into post and with post admin panel use checkbox to view on front

Categories