I'm trying to rename files while uploading them to WordPress and I want them to get the name of sanitized post title.
Basically I want to do same thing as here, but unfortunately when I use the code from this answer - I don't get the value of $post variable.
The only thing I get is "empty" name with some numbers at the end and the file extension, e.g. "-5263.png", which increses with every new file.
For some reason I don't get the $post value which would give me the post title and it just changes the file name to... well, nothing and just adding some numbers at the end, so it doesn't overrite any other file.
I really would like to know what's wrong with my code:
function new_filename( $filename, $filename_raw ) {
global $post;
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$new = $post->post_title;
if ( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new . $ext;
}
add_filter( 'sanitize_file_name', 'new_filename', 10 );
Thank you in advance for your help.
I've made a plugin a long time ago called File Renaming on Upload that can help you on this, but if you are searching for help with your code i can say that you can try a different approach to get the post variable. Try this instead:
function get_post() {
global $post;
$post_obj = null;
if( !$post ){
$post_id = isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : false;
if ( $post_id && is_numeric( $post_id ) ) {
$post_obj = get_post( $post_id );
}
}else{
$post_obj = $post;
}
return $post_obj;
}
Once you get your post variable, you don't need to use the post_title like that. You can use
$post->post_name
And then you don't need to use sanitize_file_name() function
Related
as you can see this code to rename images by post title works fine.
even with several posts with the same title.
it just puts the numbers: image, image1, image2, image3 .. etc
/*Renaming attachment files to the post title*/
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if ( get_post_type( $_REQUEST['post_id'] ) === 'property'){
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 );
// 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', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
I believe this code works since inside in CPT property he renames my upload to
post-title.jpg
result : post-title.jpg , post-title-1.jpg, post-title-2.jpg , post-title-3.jpg, etc....
and outside CPT property in wordpress he rename strange empty-1.jpg to uploads..
result : -1.jpg , -2.jpg , -3.jpg etc .....
I will need help to add some instructions
I must miss an instruction to tell him ,it should only fire in CPT property only
else --> do nothing if there is no title and if we are not in CPT property.
so he does not rename the uploads to 'auto-draft.jpg' when no title set and image uploaded first .. very annoying.. and if we are outside CPT'property' do nothing = leave the names of the original uploads and ignore this code.
I think simply commenting (or removing) these two lines in your file_renamer() function will do the trick:
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
Because if ( get_post_type( $_REQUEST['post_id'] ) === 'property'){ is the line that checks whether the post_id belong to a Custom Post Type. Based on what I understood from your explanation, you only want do the renaming there. If you want to do something else too, you could write inside that IF condition.
So your code would look like this:
/*Renaming attachment files to the post title*/
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if ( get_post_type( $_REQUEST['post_id'] ) === 'property'){
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;
}
}
Btw, I didn't tested the code!
I am trying to create my custom front-end upload of users avatars.
I created form and created custom fields/meta data for it but I have problems with overriding get_avatar() wordpress function and I occurred with next problems.
My function can't get userId and size, I tried multiple solutions but I can't find solution why my get_avatar wont accept size and userID or userEmail
Code in functions.php
add_filter( 'get_avatar' , 'my_get_avatar' );
function my_get_avatar( $user_id, $size = '', $default = '', $alt = false ) {
var_dump($size);
if ( empty( $size ) || ! is_numeric( $size ) ) {
$size = 96;
}
$custom_avatar = get_user_meta( $user_id, '_user_avatar', true );
if(!($custom_avatar))
{
$url = "https://webkit.org/demos/srcset/image-src.png";
}
var_dump($custom_avatar);
$html = sprintf('<img src="%s" width="%s" height="%s" class="Avatarmss">', $url, $size,$size);
return $html;
}
When I put var_dump of $userID i get string with img tag and gavatar source
<img alt='' src='http://1.gravatar.com/avatar/d10ca8d11301c2f4993ac2279ce4b930?s=32&d=mm&r=g' .....
For dumping of size I get empty string.
I found solution.. Every core function is called before functions.php so I created custom plugin for this
try
add_filter( 'get_avatar','my_get_avatar' , 10, 5 );
I have created a custom post type in WordPress but wondering if its possible to specify an upload directory specific to the custom post type and when doing and inserting of media that the media library only show the media uploaded into the specific directory for the custom post type.
save images in and media library only shows media in:
/wp-content/uplodas/custom_post_type/
UPDATE
I have the following code which will filter the content i'm looking for HOWEVER i only want to run the filter if im on the CPT of client_gallery. My if statment doesnt seem to work?
function wpse48677_get_cpt()
{
if ($_GET['post_type'] == "") {
$posts = $_GET['post'];
$postType = get_post_type($posts);
} else {
$postType = $_GET['post_type'];
}
return $postType;
}
function my_posts_where($where)
{
global $wpdb;
$post_id = false;
if (isset($_POST['post_id'])) {
$post_id = $_POST['post_id'];
$post = get_post($post_id);
if ($post) {
$where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type);
}
}
return $where;
}
function my_posts_join($join)
{
global $wpdb;
$join .= " LEFT JOIN {$wpdb->posts} as my_post_parent ON ({$wpdb->posts}.post_parent = 'client_gallery') ";
return $join;
}
function my_bind_media_uploader_special_filters($query)
{
add_filter('posts_where', 'my_posts_where');
add_filter('posts_join', 'my_posts_join');
return $query;
}
print wpse48677_get_cpt();
if(wpse48677_get_cpt() == 'client_gallery') {
// THIS IF STATEMENT DOESNT SEEM TO WORK? I KNOW $doJoin == client_gallery
// AS I CAN SEE IT IF I PRINT IT OUT (see above)
// IF I RUN THE ADD FILTER WITHOUT THE IF I GET THE RESULTS I"M LOOKING FOR?????
add_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters');
}
you will make an upload dir for your custom post type if you add this code wherever your custom post type declaration happens. this will also use this folder everytime your upload happens from a post where the post type is yours.
function super_upload_dir( $args ) {
if(!isset($_REQUEST['post_id']) || get_post_type( $id ) != $YOUR_POST_TYPE)
return $args;
$id = ( isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : '' );
if( $id ) {
$newdir = '/' . $DIRECTORY_NAME;
$args['path'] = str_replace( $args['subdir'], '', $args['path'] );
$args['url'] = str_replace( $args['subdir'], '', $args['url'] );
$args['subdir'] = $newdir;
$args['path'] .= $newdir;
$args['url'] .= $newdir;
}
return $args;
}
add_filter( 'upload_dir', 'super_upload_dir' );
for the librairy filter, ive used plugins in the past that had a way to filter media items based on a shortcode, but i wouldnt know off the bat what to do to get it filtered based on current post type in the backend. sorry
I have a div with inputs within it in my document, and I would like to be able to save more than just each input's value in a function, run during the save_post hook. for testing, it looks like this at the moment:
$sanitized_data = array();
foreach ( $resources as $index=>$resource ) {
$resource = esc_url( strip_tags( $resource ) );
if ( ! empty( $resource ) ) {
$sanitized_data[$index] = $resource;
}
}
$myDocument->update_post_meta(
$post_id,
'Meta_key',
$sanitized_data
);
I'm not sure how to retrieve any other information, and I suspect when the save_post action is run the document no longer exists, only the meta data, or at least that's the way it seems.
I created this function to try and see what was going on:
$elements = $this->getElementsByTagName('input_wrapper');
foreach($elements as $index=>$child) {
var_dump( $child );
}
die();
Unfortunately, this comes up with nothing but a blank screen. Can anyone help me?
EDIT: More Code.
Problem: I want to get the post meta of a post. It works fine for the case updated_post, but not for new_post and I just can't figure out why..
This is the function for the cases:
function userpro_sc_new_post( $new_status, $old_status, $post ) {
global $userpro_social;
$exclude = userpro_sc_get_option('excluded_post_types');
if ($exclude != ''){
$exclude_types = explode(',',$exclude);
} else {
$exclude_types = array('nav_menu_item');
}
if (!in_array($post->post_type, $exclude_types )) {
// new post
if ( $new_status == 'publish' && $old_status != 'publish' ) {
$user = get_userdata($post->post_author);
$userpro_social->log_action( 'new_post', $user->ID, $post->ID, $post->post_title, $post->post_type );
}
// updated post
if ($new_status == 'publish' && $old_status == 'publish' ){
$user = get_userdata($post->post_author);
$userpro_social->log_action( 'update_post', $user->ID, $post->ID, $post->post_title, $post->post_type );
}
}
}
And this is the code to run in the cases:
function log_action($action, $user_id, $var1=null, $var2=null, $var3=null) {
global $userpro, $userpro_social;
$activity = get_option('userpro_activity');
$timestamp = current_time('timestamp');
$status = '';
switch($action){
case 'new_post':
$myId = get_post_meta(get_the_ID(), 'wpex_post_video_oembed', true);
$status .= $myId;
break;
case 'update_post':
$myId = get_post_meta(get_the_ID(), 'wpex_post_video_oembed', true);
$status .= $myId;
break;
}
Like I said, update_post works so I can see the ID... new_post does not work. Why?
I simplified the code to run a bit, but it is still the same issue.
Please help!
You have to be aware of three things before using get_post_meta() in your plugins.
You must declare global variables as global if any (eg: $wpdb).
You have to get the post data in $post_id (eg: $post_id = $_POST['postid'];).
Update the custom field value if needed (eg: update_post_meta($post_ID, 'video_id', true);).
Any of the above could be your problem. Please refer and try.
global $post;
$avriable_name=get_post_meta($post->ID, 'video_id', true);
Try the above code, global post will help to get the id for the post. If you didnt decalre it $post->ID will be blank and rest will not work.
Please let me know if you need further help.
Try this:
$myId = (get_post_meta(get_the_ID(), 'wpex_post_video_oembed',true));