How to set a value containing a percentage sign in PHPExcel - formula

I have been trying to set a value containing a percentage sign in PHPExcel.
I couldn't find how to escape it at all and all searches point me to how to format a percentage, but that's not what I need.
My current problem is:
$cell = 'Z12';
$value = '=Y12-(Y12*20%)';
$excel->setActiveSheetIndex(0)->setCellValue($cell, $value);

This problem is specific to the Excel5 Writer, the percentage operator works correctly in other writers.
I'm about to push a fix to github, but in the meanwhile you can edit the Classes/PHPExcel/Writer/Excel5/Parser.php file.
Lines 1431-1437 currently read:
if($this->_lookahead == '%'){
$result = $this->_createTree('ptgPercent', $this->_current_token, '');
} else {
$result = $this->_createTree($this->_current_token, '', '');
}
$this->_advance();
return $result;
Modify these with an extra call to $this->_advance(); for the % operator lookahead branch:
if($this->_lookahead == '%'){
$result = $this->_createTree('ptgPercent', $this->_current_token, '');
$this->_advance(); // Skip the percentage operator once we've pre-built that tree
} else {
$result = $this->_createTree($this->_current_token, '', '');
}
$this->_advance();
return $result;

Related

How to format hreflang from "en-ae" to "en-AE" (WordPress+Rank Math+WPMLl)?

I need to set it by the technical task.
I've found only
function hrefs_to_uppercase($hrefs) {
$hrefs = array_change_key_case($hrefs,CASE_UPPER);
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
But it makes all characters uppercase - "EN-AE".
Tried manually in wpml settings- didn't help
You can simply replace the array key with the following code:
function hrefs_to_uppercase($hrefs) {
$hrefs['en-AE'] = $hrefs['en-ae'];
unset($hrefs['en-ae']);
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
if you want to make every array key have an uppercase second part (e.g. from en-us to en-US), you can use the codes below (assumed all your keys have a similar structure like en-us):
function hrefs_to_uppercase($hrefs) {
foreach ($hrefs as $key => $val) {
$key_tokens = explode('-', $key);
$new_key = $key_tokens[0] . '-' . strtoupper($key_tokens[1]);
$hrefs[$new_key] = $hrefs[$key];
unset($hrefs[$key]);
}
return $hrefs;
}
add_filter( 'wpml_hreflangs', 'hrefs_to_uppercase' );
I solved like that for now, maybe right-maybe not
jQuery('[hreflang*="en-ae"]').each(function(){
// Update the 'rules[0]' part of the name attribute to contain the latest count
jQuery(this).attr("hreflang",'en-AE');
});

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);
});
}
});

PHPexcel - getOldCalculatedValue and rangeToArray

Searched for quite a while now, but I'm stuck at the following problem.
I am using PHPexcel 1.8.0
The spreadsheet is read using the following code:
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, TRUE);
So far ok and it works well.
But some spreadsheets contain external referenced data.
And for that I want to use "getOldCalculatedValue".
How do I combine "getOldCalculatedValue" with "rangeToArray" ?
Or is "rangeToArray" inappropriate for this ?
Thanks for any help or hints !
Simple answer, you can't combine the two
rangeToArray() is a simple method for a simple purpose, it doesn't try to do anything clever, simply to return the data from the worksheet as efficiently and quickly as possible
getOldCalculatedValue() is used for a very specific circumstance, and isn't guaranteed to be correct even then, because it retrieves the last value calculated for the cell in MS EXcel itself, which ,ay not be correct if the external workbook wasn't available to MS Excel in that circumstance, or MS Excel formula evaluation was disable.
When calculating cells values from a formula, the PHPExcel calculation engine should use the getOldCalculatedValue() as a fallback if it finds an external reference, and rangeToArray() will try to use this method, but it isn't perfect, especially when that reference in nested deep inside other formulae referenced in other cells.
If you know that a formula in a cell contains an external reference, you should use getOldCalculatedValue() directly for that cell
I came up with the following solution.
Maybe not perfect, but it currently does the job. Thanks for any improvements!
With PHPExcel included and the excel file uploaded and ready, I continue with:
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
Create a new array to store the cell values of a row
$arr_row = array();
Loop through the rows
for ($rownumber = 2; $rownumber <= $highestRow; $rownumber++){
$row = $sheet->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
Then loop through the cells of the current row
foreach ($cellIterator as $cell) {
Find cells with a formula
$cellcheck = substr($cell->getValue(),0,1);
if($cellcheck == '='){
$cell_content = $cell->getOldCalculatedValue();
}
else{
$cell_content = $cell->getValue();
}
Add the cell values to the array
array_push($arr_row,$cell_content);
Close cell loop
}
At this point I use the $arr_row to do further calculations and string formatting, before finally inserting it into a mysql table.
Close row loop
}
I made some changes in the function rangeToArray() inside Worksheet.php.
Worked fine!
public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Returnvalue
$returnValue = array();
// Identify the range that we need to extract from the worksheet
list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange);
$minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1);
$minRow = $rangeStart[1];
$maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1);
$maxRow = $rangeEnd[1];
$maxCol++;
// Loop through rows
$r = -1;
for ($row = $minRow; $row <= $maxRow; ++$row) {
$rRef = ($returnCellRef) ? $row : ++$r;
$c = -1;
// Loop through columns in the current row
for ($col = $minCol; $col != $maxCol; ++$col) {
$cRef = ($returnCellRef) ? $col : ++$c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
// so we test and retrieve directly against _cellCollection
if ($this->_cellCollection->isDataSet($col.$row)) {
// Cell exists
$cell = $this->_cellCollection->getCacheData($col.$row);
if ($cell->getValue() !== null) {
if ($cell->getValue() instanceof PHPExcel_RichText) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
} else {
if ($calculateFormulas)
{ ##################################### CHANGED LINES
if(!preg_match('/^[=].*/', $cell->getValue()))
{
$returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); # THE ORIGINAL CODE ONLY HAD THIS LINE
}
else
{
$returnValue[$rRef][$cRef] = $cell->getOldCalculatedValue();
}
} ##################################### CHANGED LINES
else
{
$returnValue[$rRef][$cRef] = $cell->getValue();
}
}
if ($formatData) {
$style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString(
$returnValue[$rRef][$cRef],
($style && $style->getNumberFormat()) ?
$style->getNumberFormat()->getFormatCode() :
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
}
} else {
// Cell holds a NULL
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
// Cell doesn't exist
$returnValue[$rRef][$cRef] = $nullValue;
}
}
}
// Return
return $returnValue;
}

Rename files during upload within 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?

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