I'm using the code bellow (I found it here on stack overflow from this post) to auto rename image filename and fill alt and title field based on post title.
The good thing is it's working, it's doing its job but problem is with filename : it's using post title with spaces, comas, etc. as filename, which is really not good. It's perfect for filling the title and alt fields but not for a filename.
So, just for the filename, I would like to add something to replace spaces by hyphen (and if possible remove potentials comas or other punctuation)
I thought that the part add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 ); would to the job, but it's not.
But as I'm really not sure what I'm doing, and as I have poor PHP knowledge, I would be very grateful if you could teach me how to make it work :
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $filename;
}
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
/* Automatically set the image Title, Alt-Text, Caption & Description upon upload */
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
if ($post_id != false) {
$my_image_title = get_the_title($post_id);
} else {
$my_image_title = get_post( $post_ID )->post_title;
}
// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $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_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', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
Thanks for your help !
So solution was replacing post_title by post_name in file_renamer function.
Exactly this part : change return $post->post_title . $ext; and replace it with return $post->post_name . $ext;
And it's working. On upload, this function is renaming the file name with hyphens and filling title, alt text and description fields based on Post Title (without hyphens).
Related
I want to add extra information after every name, in the name columns cells, How may I do that? default columns like names, email, role are not pass on manage_users_custom_column hook. I tried the below code but not working!
add_filter( 'manage_users_custom_column', 'add_extra_text_after_every_name', 10, 3 );
function add_extra_text_after_every_name( $output, $column_name, $user_id ) {
if ( 'name' == $column_name ) {
// is not working, because default fields name didn't pass
}
return $output;
}
thanks in advance for your reply.
You can't because that field is from wordpress default swtich cases, so this never will take that filter, you can see this in the wordpress/wp-admin/includes/class-wp-users-lists-table.php line #547
case 'name':
if ( $user_object->first_name && $user_object->last_name ) {
$r .= "$user_object->first_name $user_object->last_name";
} elseif ( $user_object->first_name ) {
$r .= $user_object->first_name;
} elseif ( $user_object->last_name ) {
$r .= $user_object->last_name;
} else {
$r .= sprintf(
'<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
_x( 'Unknown', 'name' )
);
}
break;
The only thing that you can do, is add new columns and data
I have a wordpress website where customers make an image with text and icons, once processed thru woocommerce and payed for that image name 12345.png is saved as Customer_product_image
function add_order_item_meta($item_id, $values) {
$key = 'customer_product_image'; // Define your key here
$value = $values['user_img']; // Get your value here
woocommerce_add_order_item_meta($item_id, $key, $value);
}
And i works great, but now i'm banning my head against the wall! When the purchased image is displayed on the Order admin detail page, it shows up as CUSTOMER_PRODUCT_IMAGE: 1234.png how on earth would i go about wrapping that within an image tag so the image is displayed there?
I've searched high and low on google but haven't been able to find anything, its probably that i dont know what do actually search for....
This did the trick for me!
First i added this snippet for removing the custom meta item on order detail render:
add_filter( 'woocommerce_hidden_order_itemmeta', 'hide_order_item_meta_fields' );
function hide_order_item_meta_fields( $fields ) {
$fields[] = 'current_view';
$fields[] = 'custom_image';//Add all meta keys to this array,so that it will not be displayed in order meta box
return $fields;
}
second i added it back with this, and with the desired text and image tag:
add_action( 'woocommerce_after_order_itemmeta', 'order_meta_customized_display',10, 3 );
function order_meta_customized_display( $item_id, $item, $product ){
$all_meta_data=get_metadata( 'order_item', $item_id, "", "");
$useless = array(
"_qty","_tax_class","_variation_id","_product_id","_line_subtotal","_line_total","_line_subtotal_tax","_line_tax","_line_tax_data"
);// Add key values that you want to ignore
$customized_array= array();
foreach($all_meta_data as $data_meta_key => $value) {
if(!in_array($data_meta_key,$useless)){
$newKey = ucwords(str_replace('_'," ",$data_meta_key ));//To remove underscrore and capitalize
$customized_array[$newKey]=ucwords(str_replace('_'," ",$value[0])); // Pushing each value to the new array
}
}
if (!empty($customized_array)) {
foreach($customized_array as $data_meta_key => $value){
echo "<div class='product_container'><span>Produkt Billede: </span><img src='".wp_upload_dir()['baseurl'].'/flapper/'. $value ."' /> </div>";
}
}
}
i found the answer to this question on this page
You can use the filter woocommerce_order_item_display_meta_value to output the image. Place this code in your functions.php file, you'll need to modify the src attribute of the img tag to include the appropriate URL before the filename value. You can also modify the display label with the filter woocommerce_order_item_display_meta_key
add_filter( 'woocommerce_order_item_display_meta_value', 'modify_order_item_display_value' , 10, 3 );
function modify_order_item_display_value( $display_value, $meta, $wc_order_item ) {
$meta_data = $meta->get_data();
if( $meta_data['key'] === 'customer_product_image' ) {
return '<img src="' . $meta_data['value'] . '">';
}
return $display_value;
}
add_filter('woocommerce_order_item_display_meta_key', 'modify_order_item_display_key', 10, 3);
function modify_order_item_display_key( $display_key, $meta, $wc_order_item ) {
$meta_data = $meta->get_data();
if( $meta_data['key'] === 'customer_product_image' ) {
return 'Customer Image';
}
return $display_key;
}
I'm attempting to add a feature to a plugin that extends media management. This feature would allow you to rename an attachment file. I've been able to complete this with the following code.
public function update_attachment_filename( $post_ID ) {
// Get path to existing file
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Generate new file name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the name and reference to file
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
}
While the original file gets renamed using the above method, all additional image sizes defined in the plugins/theme are not updated. I'm struggling to figure out the best way to accomplish this task.
I've looked into wp_update_attachment_metadata() and wp_generate_attachment_metadata() but am unsure whether they will give me the desired functionality.
Additionally I've looked into something such as:
$file_meta = wp_get_attachment_metadata( $post_ID );
foreach( $file_meta['sizes'] as $image ) {
// Do something
}
Any nudge in the right direction would be greatly appreciated.
Thanks!
I was able to utilize both the wp_generate_attachment_metadata() and the wp_update_attachment_metadata() function to achieve the desired end result.
public function update_attachment_filename( $post_ID ) {
if( isset( $_POST['update_filename'] ) && ! empty( $_POST['update_filename'] ) ) {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the attachment name
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
}
}
Entirely Revised Please Reread
Hello,
The theme I am using displays the page's title as opposed to it's menu label in the breadcrumbs. I am trying to get the breadcrumbs to instead display the associated menu label if it is available and if not then default to the page_title.
I have come up with some code that I think is close. Line 4/// $menu_items = wp_get_nav_menu_items( $slug ); returns null and it should return the nav item that contains $slug of the current post. Obviously, there is something I do not understand.
What I am attempting to do is get the slug of the current post, then using the slug get the nav item post. Then extract the title of the nav item and use that in place of the page title in the breadcrumbs. If the page was not in the nav system then it should default to the page title, as might be the case for a ppc campaign landing page.
if ( is_page() && !$post->post_parent ) {
$title = null;
$slug = mpactMEDIA_get_the_slug( get_the_ID() );
$menu_items = wp_get_nav_menu_items( $slug );
//var_dump((array)$menu_items);
foreach ( (array)$menu_items as $key => $menu_item ) {
$title = $menu_item->post_title;
}
if ( $title ) { echo $delimiter . ' ' . $before . $title . $after; }
else { echo $delimiter . ' ' . $before . get_the_title() . $after; }
}
I'm my functions.php file I have the following function
function mpactMEDIA_get_the_slug( $id=null ){
if( empty($id) ) global $post;
if( empty($post) ) return '';
$id = $post->ID;
endif;
$slug = basename( get_permalink($id) );
return $slug;
}
Thank you in advance,
Tim
I read the question a few times, I got here searching for an answer, ended up making my own.
function get_menu_label_by_post_id($post_id, $menu) {
$menu_title = '';
$nav = wp_get_nav_menu_items($menu);
foreach ( $nav as $item ) {
if ( $post_id == $item->object_id ) {
$menu_title = $item->post_title;
break;
}
}
return ($menu_title !== '') ? $menu_title : get_the_title($post_id);
}
Example usage:
echo get_menu_label_by_post_id($post->ID, 'Primary Nav');
This will return what the menu label is if it finds it, otherwise just the title of the post ID.
Check the documentation for wp_get_nav_menu_items. It doesn't take a page slug as a parameter at all.
If you want to list child pages of a given page, use wp_list_pages and pass a child_of parameter to it.
Also, as a side note, if you know the $post and want the slug, it's just $post->post_name
[amazon_s3 bucket=my_bucket_name object=my_file_name.ext]
Hi all i need to know how to fetch the parameter value in the above shortcode. For Example: Object is the attributes then how can i fetch the object value my_file_name.ext. I am using the woocommerce s3 plugin. I am not sure i customized the woocommerce to fetch the file name show in my account page here is the code.
function filename_wc_downloads( $link, $download )
{
$order = new WC_Order( $download['order_id'] );
$download_file_urls = $order->get_downloadable_file_urls(
$download['product_id'],
null,
$download['download_id']
);
foreach( $download_file_urls as $key => $value )
{
if( $value == $download['download_url'] )
{
$url_parts = explode( '/', parse_url( $key, PHP_URL_PATH ) );
$file_name = end( $url_parts );
$link = '<a href="'
. esc_url( $download['download_url'] )
. '">'
. $download['download_name']
. '</a> <small>( '
. $file_name
. ' )</small>';
}
}
return $link;
}
In a Woocommerce all products are uploaded into the media library of upload folder. The above code is to fetch the filename show in my account page if they using direct file path. If i pasted the above shortcode in the product url, that above code doesn't help to fetch the filename. so i need to know from the shortcode how can i get the object value based on this to show the file name.
amazon_s3 is your shortcode containing $atts bucket and object
when you use wordpress function add_shortcode('amazon_s3', 'your_function_name');
it automatically converts your attributes defined in [amazan_s3 .... to $atts
e.g.
function your_funnction_name($atts) {
extract(shortcode_atts(array(
'bucket' => '',
'object' => ''
), $atts));
return $object;
}