Change wordpress gallery shortcode slug to filename - wordpress

Is it possible to change the attachment page slug to the referring filename? In short... i use the Gallery Shortcode to build a simple page based gallery.
I change the orignal filename (like DSC1223.jpg) during the upload process (to 3b1871561aab.jpg) but it does not appery as slug within the url. It uses only DSC1223.
Is there anyway to change ist?
Regards, Steve
The best way would be to write something like this in my functions.php
function twentyten_filter_wp_handle_upload () {
$upload = wp_handle_upload();
}
add_filter( 'wp_handle_upload', 'twentyten_filter_wp_handle_upload', 10, 2);

Add this to the hash upload filename plugin and you should be good to go;
/**
* Filter new attachments and set the post_name the same as the hashed
* filename.
*
* #param int $post_ID
*/
function change_attachment_name_to_hash($post_ID)
{
$file = get_attached_file($post_ID);
$info = pathinfo($file);
$name = trim( substr($info['basename'], 0, -(1 + strlen($info['extension'])) ) );
wp_update_post(array(
'ID' => $post_ID,
'post_name' => $name
));
}
add_action('add_attachment', 'change_attachment_name_to_hash');
Don't hesitate to ask if you're not sure what each line does!
UPDATE:
This function hooks onto the add_attachment event, just after a new attachment is saved to the database. This action is called from within wp_insert_attachment().
We first grab the filename of the attachment (get_attached_file()). Then we use a native PHP function pathinfo() to get the path components, and strip the directory path and file extension away.
Then we call wp_update_post(), updating the post_name of the attachment in the database.

Related

Delete Gravity Forms file attachments after submission but keep all other fields?

OK, we have a job submission form on the site where users need to complete the form and attach resume and cover letter. For privacy reasons, we do not want to keep the resumes and cover letters on the server, so what we've been doing is send emails with form submission, attach resume and cover letter, and then completely delete the submission.
This is the code we've been using and everything works the way it should.
/**
*
* Target submissions from form ID 2.
*
* Change gform_after_submission_2 to reflect your target form ID,
* or use gform_after_submission to target all forms.
*
*/
add_action( 'gform_after_submission_2', 'remove_form_entry' );
function remove_form_entry( $entry ) {
GFAPI::delete_entry( $entry['id'] );
}
I was wondering if there's a way to keep the form entries but just delete the attachments?
I have just wrote the function, tested and it works fine to delete resume file.
You can add more code same way for cover letters.
add_filter( 'gform_after_submission_2', 'remove_form_entry', 10, 2 );
function remove_form_entry( $entry, $form ) {
global $wpdb;
$lead_id = $entry['id'];
$meta_key = 1; //it is the uploads field id.
$entry_table = $wpdb->prefix . 'gf_entry_meta'; //meta table of gravity forms
$get_resume_file_statement = $wpdb->prepare( "SELECT `meta_value` FROM `$entry_table` WHERE `meta_key` = %d AND `entry_id` = %d", $meta_key, $lead_id);
$meta_values_of_resume_file = $wpdb->get_col( $get_resume_file_statement ); // get uploaded csv file url
$resume_url = explode('uploads', $meta_values_of_resume_file [0]); //get file url after uploads folder. It returns file url like http://localhost/g2a/wp-content/uploads/gravity_forms/3-dbbe121585c30ed9e49ec2a6803270b0/2021/07/89636498_188586552577282_8867025936109797376_n.jpg
$resume_file_name = end($resume_url ); //get file url after uploads folder. value like /gravity_forms/3-dbbe121585c30ed9e49ec2a6803270b0/2021/07/89636498_188586552577282_8867025936109797376_n.jpg
$upload_dir = wp_upload_dir(); //uploads dir
$full_path = $upload_dir['basedir'] . $resume_file_name; //get full path of file
wp_delete_file( $full_path ); //delete the file
//update entry meta field value here or delete the entry meta.
}

WooCommerce renaming a digital download file

I've been using woocommerce to sell a few digital goods. I have set the following setting "Append a unique string to filename for security" And I was wondering if there is a way to rename the file back to it's original name when the customer downloads it.
For example the filename is product-9j978f.zip and when the customer downloads it would be renamed to product.zip instead.
Thank you and any help would be gladly appreciated
Here is the code
/**
* Change the downloadable file name
*
* #param string $filename Downloadable file name.
* #param int $product_id WC product id.
* #return string
*/
function change_woocommerce_file_download_filename( $filename, $product_id ) {
// Get the file extension from the processed file name.
$filetype = wp_check_filetype( $filename );
// You can generate a new file using Product ID if you need to.
$new_file_name = 'New File Name';
// Join the new file name with file extension with (.).
return join( '.', array( $new_file_name, $filetype['ext'] ) );
}
add_filter( 'woocommerce_file_download_filename', 'change_woocommerce_file_download_filename', 10, 2 );
You get 2 parameters in this filter hook. 1: Filename 2: Product ID then you can do the name change according to your need and return the file name.
NOTE: new file name should have a file extension with it.

Use ACF load_value hook to pre-populate the Upload File field

I'm trying to pre-populate the File upload field with files already submitted previously, using ACF PRO and ACF Frontend Form.
So far, I am able to retrieve a list of files that was previously uploaded but can't seem to figure out a way to set it in the file upload frontend.
The File upload field lives inside a Repeater group.
In the functions.php:
I added a load_value with key set to the repeater group:
add_filter('acf/load_value/key=field_5e80ed8f4516b', 'my_acf_set_file_list', 10, 3);
Then in the function I attempted to set the $value to be an array of file urls.
'field_5e80edf14516c' is the key for the File field.
function my_acf_set_file_list( $value, $post_id, $field ){
$order_id = $_GET['order'];
$value = array();
// get existing files
$existing_files = get_post_meta( $order_id, 'file', true);
if ( !empty( $existing_files ) ) {
$i = 0;
foreach ( $existing_files as $file ) {
$value[$i]['field_5e80edf14516c'] = $file;
// also tried
// $value[$i]['field_5e80edf14516c'] = $file['file'];
}
}
return $value;
}
The problem is in the frontend form, there seems to be no change at all. No file was pre-populated.
I'm pretty sure I didn't get the array structure correct, but I've searched all over and cannot find any related information.
The post data for when I upload existing files seem to indicate the attachment ID is used. But I'm not sure what is the row-0 and other id 5ebf042bba99f?
acf[field_5e80ed8f4516b]:
acf[field_5e80ed8f4516b][row-0][field_5e80edf14516c]: 381
acf[field_5e80ed8f4516b][5ebf042bba99f][field_5e80edf14516c]: 381
acf[field_5e80ed8f4516b][5ebf042cba9a0][field_5e80edf14516c]: 401
Thanks in advance!

Change custom postType properties from parent theme in Wordpress

I'm building a childtheme for an excisting Wordpress theme.
The parent theme creates a custom post type, that has a property "rewrite" property that I would like to get rid of.
'rewrite' => array(
'slug' => 'project'
)
I found that it is possible to alter / add taxonomies on excisting custom post types like this:
register_taxonomy_for_object_type( 'category', 'CUSTOM_POST_NAME' );
But is it posible to change this (and other) properties?
The key here is the call to register_post_type. This is what actually registers the post type within WordPress.
In the docs, we see that the function is defined in /wp-includes/post.php. We can also see the full source code of the function, which is very handy.
In the source code of the function, we can see that there's only a single do_action() and that's called after the post type is fully registered.
So, the next place to look at is in the WP_Post_Type class. We can again expand the full source code(or you can look through the source code in your favorite text/code editor). The first place to look at is the __construct() method of the class. This currently(WordPress 4.8) consists of the following:
public function __construct( $post_type, $args = array() ) {
$this->name = $post_type;
$this->set_props( $args );
}
So, as you can see, the name is assigned to $this->name and then the method set_props() is called with the passed $args(which is the array of parameters sent to register_post_type().
The next logical place to look at is inside of the set_props() method. And at pretty much the very top of that method is the following code:
/**
* Filters the arguments for registering a post type.
*
* #since 4.4.0
*
* #param array $args Array of arguments for registering a post type.
* #param string $post_type Post type key.
*/
$args = apply_filters( 'register_post_type_args', $args, $this->name );
Bingo! The passed $args are passed through the register_post_type_args filter before they're used in initializing the post type.
So now, the final piece of the puzzle is to create your own function, attach it to the register_post_type_args filter, make sure you're changing the correct post type and you're free to do whatever you want with that post type. Here's a sample code to help you out:
function my_filter_register_post_type_args( $args, $post_type ) {
// We only want to edit the 'CUSTOM_POST_NAME' post type - if that's not it, then bail
if ( 'CUSTOM_POST_NAME' != $post_type ) {
return $args;
}
$args['rewrite'] = false;
return $args;
}
add_filter( 'register_post_type_args', 'my_filter_register_post_type_args', 10, 2 );
I hope this will help you and anyone else out there see how easy it can be to dive into the source code of WordPress(you can even do it from your browser now :) ) in order to figure out something that might not always be just a search away. With some critical thinking, you can follow the breadcrumb trail in order to figure out what the best way to tweak something is.

Wordpress Validate New Nicename/Slug

I have written a custom "Edit Account" script that allows a Wordpress user to update their Wordpress account. Everything is working great, except that I can't seem to find a way to update the user's nicename, which also doubles as the user's URL slug (via the get_author_posts_url function). This is causing issues because when a user changes their name, their slug still contains their original name - not the new one.
I know that the sanitize_title function will generate the new nicename, but I don't know how to verify that it is unique and modify it if it is not before entering it into the DB. I am wondering what built-in functions Wordpress has to handle this. I know I can write my own script to do this, but I would much rather use Wordpress functions. I couldn't find this anywhere in the WP documentation. Thanks!
Here is a function I have written to in lue of a built in function:
function new_user_slug($string){
//GENERATE NEW SLUG
$slug=sanitize_title($string);
//MAKE SURE SLUG IS UNIQUE
$result=mysql_query("SELECT * FROM wp_users WHERE user_nicename='$slug'");
if(mysql_num_rows($result)==0){
return $slug;
}else{
$counter=2;
$kill=0;
while($kill==0){
$mod_slug=$slug."-".$counter;
$result=mysql_query("SELECT * FROM wp_users WHERE user_nicename='$mod_slug'");
if(mysql_num_rows($result)==0){
$kill=1;
}else{
$counter++;
}
}
return $mod_slug;
}
}
This takes a string (the user's updated name) and converts it into the default slug. It then checks the slug against the database to see if it is unique. If it is, the slug is returned. If not, it enters an iteration loop that incrementally changes the slug until it is unique.
Try this:
wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent )
Source: https://codex.wordpress.org/Function_Reference/wp_unique_post_slug
Actually if you use wordpress user functions like wp_insert_user and wp_update_user Wordpress itselt handles duplicate user_nicename entries and adds -n suffix to them.
So your code would be something like this:
function new_nicename( $user_id, $nicename ) {
$nicename = sanitize_title( $nicename );
$user_id = wp_update_user( array( 'ID' => $user_id, 'user_nicename' => $nicename ) );
}

Resources