Rename files during upload within Wordpress - wordpress

I am trying to rename upload filenames match the Post Title.
This other thread shows how to rename to hash:
Rename files during upload within Wordpress backend
Using this code:
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
Does anyone know the code to rename the file to match Post Title.extension?

barakadam's answer is almost correct, just a little correction based on the comment I left below his answer.
function new_filename($filename, $filename_raw) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$new = $post->post_title . $ext;
// the if is to make sure the script goes into an indefinate loop
if( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new;
}
add_filter('sanitize_file_name', 'new_filename', 10, 2);
Explanation of code:
Lets assume you upload a file with the original filename called picture one.jpg to a post called "My Holiday in Paris/London".
When you upload a file, WordPress removes special characters from the original filename using the sanitize_file_name() function.
Right at the bottom of the function is where the filter is.
// line 854 of wp-includes/formatting.php
return apply_filters('sanitize_file_name', $filename, $filename_raw);
At this point, $filename would be picture-one.jpg. Because we used add_filter(), our new_filename() function will be called with $filename as picture-one.jpg and $filename_raw as picture one.jpg.
Our new_filename() function then replaces the filename with the post title with the original extension appended. If we stop here, the new filename $new would end up being My Holiday in Paris/London.jpg which all of us know is an invalid filename.
Here is when we call the sanitize_file_name function again. Note the conditional statement there. Since $new != $filename_raw at this point, it tries to sanitize the filename again.
sanitize_file_name() will be called and at the end of the function, $filename would be My-Holiday-in-Paris-London.jpg while $filename_raw would still be My Holiday in Paris/London.jpg. Because of the apply_filters(), our new_filename() function runs again. But this time, because $new == $filename_raw, thats where it ends.
And My-Holiday-in-Paris-London.jpg is finally returned.

Something like this? (considering $post is your post variable, make it global):
function new_filename($filename) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
return $post->post_title . $ext;
}
add_filter('sanitize_file_name', 'new_filename', 10);
Did I understand you?

Related

WordPress Nested Second Add Action is not working

Second add_action function is not working but I am not getting any error. if I take the second add_action out of the function it works outside but since I want it to work on specific pages I can't work with that.
Do you have any suggestion how may I fix this problem?
add_action('current_screen', function ($current_screen) {
if ('smart_board' == $current_screen->post_type && 'post' == $current_screen->base) {
add_action('add_attachment', function ($post_ID) {
$file = get_attached_file($post_ID);
$path = pathinfo($file);
$file_slugified_name = $path['filename'];
$file_prefix = 'smart_board_';
$file_dir = $path['dirname'];
$file_extension = $path['extension'];
$newfilename = $file_prefix . $file_slugified_name;
$newfile = $file_dir . "/" . $newfilename . "." . $file_extension;
rename($file, $newfile);
update_attached_file($post_ID, $newfile);
});
}
});

automatically generate tags from content in wordpress

my WordPress website contents have some words in every line,
I want a code to automatically convert every line in content to tag (every line not every word), let's say my content is like this:
Beagle puppy
Costumes
Wales
Dogs
I want tags from every line: Beagle puppy, Costumes, Wales, Dogs
I don't want to use plugins, because I used some but it needs a keyword list to match the content. I don't want to use any keyword list to match the content.
is it possible to convert every line in content into one tag?
Assuming you meant what you appeared to mean - for instance, that the source post consists solely of the lines to be converted, the lines won't include additional odd/inappropriate chracters to be handled, and so on - the following will work. If you need to convert a section of a post or some other element defined in some other way, or attach the lines as tags to the current post, etc., then you'll need to provide those details clearly.
Place shortcode [convert_post_lines_to_tags] in new output post.
Save draft, and preview (shortcode won't function yet, obviously)
Add functions to your theme functions.php
Provide "$source_post_id" where indicated.
Re-load output post
add_shortcode( 'convert_post_lines_to_tags', 'convert_post_lines_to_tags' ) ;
function convert_post_lines_to_tags() {
$source_post_id = '' ; //Provide ID Number of post with lines to be converted
$i = 0 ;
$newTags = 'New tags inserted: <br />' ;
//TIL - PHP requires double quotes to replace escaped characters
$post_content = str_replace(
array( "\r\n", "\r" ), ',', get_post( $source_post_id )->post_content
) ;
$post_line_array = explode( ',', $post_content ) ;
foreach ( $post_line_array as $line_tag ) {
$tag = wp_insert_term( $line_tag, 'post_tag' ) ;
if ( ! is_wp_error( $tag ) ) {
$i++ ;
$newTags .= $i . '. ' . get_term( $tag['term_id'] )->name . '<br />' ;
}
}
return $newTags ;
}

Silverstripe create a better LimitWordCount function

The framework offer LimitWordCount in StringField.php file. It's great but not totally perfect. Some tags et ponctuation needs the be corrected.
I would like :
Keep tags <sup><sub><em>
Correct ponctuation : «.» to «. », «,» to «, », «?» to «? » etc....
I have made my own LimitWordCount :
public function MyLimitWordCount($int) {
$text = strip_tags($this->owner->value, '<sup><sub><em>');
if (str_word_count($text, 0) > $int) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$int]) . '…';
}
$text = str_replace('.', '. ', $text );
$text = str_replace('!', '! ', $text );
$text = str_replace('…', '… ', $text );
$text = str_replace('?', '? ', $text );
return $text;
}
That not works totally. Some ponctuation are not corrected and video shortcodes [embed width="480...] made in an HTMLEditor fields are keep with my function. I dont' know what him doing wrong.
You'll continue to get the shortcodes in your text becuase you need to parse them first.
This is most easily resolved by using (string)$this->owner->dbObject('value') rather than $this->owner->value.
You can then manipulate the value where the shortcodes have been expanded.
I can't comment on why your punctuation is not being "corrected" in this instance as you haven't supplied much information on which punctuation and under what circumstances it isn't working.

How can I read Excel files with symfony2?

I installed Excelbundle with PhpExcel library. I want to read excel files I found this function.
How can I use it? Any suggestion?
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
My suggestion is "Read the documentation" and start hacking at it. Working with excel is, in my experience, quite complex and time consuming so don't expect other people to solve your problem online.
It seems like you're talking about this bundle:
https://github.com/liuggio/ExcelBundle
It has great documentation, even full examples (see "Fake Controller").
With PHPExcel it is quite easy to read a Excel document.
See my example :
$dir = $this->getContainer()->getParameter("kernel.root_dir") . "/../../data/import/";
$file_name = "my_excel_file.xlsx";
$excel = $this->getContainer()->get('phpexcel')->createPHPExcelObject($dir . DIRECTORY_SEPARATOR . $file_name);
$sheet = $excel->getActiveSheet();
$row = 0;
while ($sheet->getCellByColumnAndRow(1, $row)->getValue()) {
$data = $sheet->getCellByColumnAndRow(2, $row)->getValue(); // get value from nth line and 2nf column
//do stuff -- see doc for functions on $sheet
}

Wordpress - Excerpt character alternative?

I'm totally new to WordPress so be easy :)
I the following code in a template:
<?php excerpt(20);?>
What this does is limit the text with 20 words. I am now wondering if there is some sort of similar function that limits by characters instead of words?
Thanks!
I use this:
add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
return '500';
}
function better_excerpt($limit, $id = '') {
global $post;
if($id == '') $id = $post->ID;
else $id = $id;
$postinfo = get_post($id);
if($postinfo->post_excerpt != '')
$post_excerpt = $postinfo->post_excerpt;
else
$post_excerpt = $postinfo->post_content;
$myexcerpt = explode(' ', $post_excerpt, $limit);
if (count($myexcerpt) >= $limit) {
array_pop($myexcerpt);
$myexcerpt = implode(' ',$myexcerpt).'...';
} else {
$myexcerpt = implode(' ',$myexcerpt);
}
$myexcerpt = preg_replace('`\[[^\]]*\]`','',$myexcerpt);
$stripimages = preg_replace('/<img[^>]+\>/i', '', $myexcerpt);
return $stripimages;
}
And then in my theme file, I just call it in with:
better_excerpt('50') //50 being how many words I want
Useful for custom plugins/widgets too.
Wordpress doesn't support the character delimiter for the excerpt method, there's a plugin called Advanced Excerpt that does. After installing you can call the_advanced_excerpt('length=20&use_words=0')
I use this in my functions.php:
function truncate ($str, $length=10, $trailing='...'){
// take off chars for the trailing
$length-=mb_strlen($trailing);
if (mb_strlen($str)> $length){
// string exceeded length, truncate and add trailing dots
$str = mb_substr($str,0,$length);
$str = explode('. ',$str);
for( $i=0; $i<(sizeof($str)-2); $i++ ):
$newstr .= $str[$i].". ";
endfor;
return $newstr;
} else{
// string was already short enough, return the string
$res = $str;
}
return $res;
}
It should truncate to a character count, but then truncate back further to the last period before the truncation. It does get problematic when your excerpt includes links, however, or other markup - in other words, it's best to use the Excerpt field in the post rather than auto-excerpting with this function, because you can't use HTML in the excerpt field.
Please use this code for limiting post content...
<?php substr($post->post_content, 0, xy); ?> ...
Change the limit of XY....

Resources