/**
* SMART labels.
*
* Add filter to convert SMART labels.
*
* @since 1.0.0
*
* @param string $label Label text value.
* @return string Modified label text value.
*/
function wapl_smart_product_label_filter( $label ) {
global $product;
...
$label = str_replace( '{percentage}', round( $highest_percentage, apply_filters( 'wapl_filter_discount_round', 1 ) ) . '%', $label );
$label = str_replace( '{discount}', wc_price( (float) $regular_price - (float) $sale_price ), $label );
$label = str_replace( '{price}', wc_price( $regular_price ), $label );
$label = str_replace( '{saleprice}', wc_price( $sale_price ), $label );
$label = str_replace( '{delprice}', '<del>' . wc_price( $regular_price ) . '</del>', $label );
return $label;
}
add_filter( 'wapl_product_label', 'wapl_smart_product_label_filter' );
{discount} или {price} или ...
, либо обработать фильтр 'wapl_product_label'
Или лучше в VBA погрузиться для решения подобных задач?
Function FilenamesCollection(ByVal FolderPath As String, Optional ByVal Mask As String = "", _
Optional ByVal SearchDeep As Long = 999) As Collection
' © EducatedFool excelvba.ru/code/FilenamesCollection
' Получает в качестве параметра путь к папке FolderPath,
' маску имени искомых файлов Mask (будут отобраны только файлы с такой маской/расширением)
' и глубину поиска SearchDeep в подпапках (если SearchDeep=1, то подпапки не просматриваются).
' Возвращает коллекцию, содержащую полные пути найденных файлов
' (применяется рекурсивный вызов процедуры GetAllFileNamesUsingFSO)
Set FilenamesCollection = New Collection ' создаём пустую коллекцию
Set FSO = CreateObject("Scripting.FileSystemObject") ' создаём экземпляр FileSystemObject
GetAllFileNamesUsingFSO FolderPath, Mask, FSO, FilenamesCollection, SearchDeep ' поиск
Set FSO = Nothing ' очистка строки состояния Excel
End Function
Function GetAllFileNamesUsingFSO(ByVal FolderPath As String, ByVal Mask As String, ByRef FSO, _
ByRef FileNamesColl As Collection, ByVal SearchDeep As Long)
' перебирает все файлы и подпапки в папке FolderPath, используя объект FSO
' перебор папок осуществляется в том случае, если SearchDeep > 1
' добавляет пути найденных файлов в коллекцию FileNamesColl
On Error Resume Next: Set curfold = FSO.GetFolder(FolderPath)
If Not curfold Is Nothing Then ' если удалось получить доступ к папке
' раскомментируйте эту строку для вывода пути к просматриваемой
' в текущий момент папке в строку состояния Excel
' Application.StatusBar = "Поиск в папке: " & FolderPath
For Each fil In curfold.Files ' перебираем все файлы в папке FolderPath
If fil.Name Like "*" & Mask Then FileNamesColl.Add fil.Path
Next
SearchDeep = SearchDeep - 1 ' уменьшаем глубину поиска в подпапках
If SearchDeep Then ' если надо искать глубже
For Each sfol In curfold.SubFolders ' перебираем все подпапки в папке FolderPath
GetAllFileNamesUsingFSO sfol.Path, Mask, FSO, FileNamesColl, SearchDeep
Next
End If
Set fil = Nothing: Set curfold = Nothing ' очищаем переменные
End If
End Function
Sub LoopThroughFiles(ByVal sDirName As String, ByRef lRow As Long, ByVal sMask As String)
On Error Resume Next
Dim folder$, coll As Collection
Dim EX As Excel.Application
Dim wkb As Workbook
Dim wks As Worksheet
Dim file As Variant
Dim i As Long
Dim v As Variant
folder$ = sDirName
If Dir(folder$, vbDirectory) = "" Then
MsgBox "Не найдена папка «" & folder$ & "»", vbCritical
Exit Sub ' выход, если папка не найдена
End If
Set coll = FilenamesCollection(folder$, sMask) ' получаем список файлов по маске из папки
If coll.Count = 0 Then
' MsgBox "В папке «" & Split(folder$, "\")(UBound(Split(folder$, "\")) - 1) & "» нет ни одного подходящего файла!", _
vbCritical, "Файлы для обработки не найдены"
Exit Sub ' выход, если нет файлов
End If
Set EX = New Application
EX.Visible = False
' перебираем все найденные файлы
For Each file In coll
Cells(lRow, 2) = CStr(file)
Set wkb = EX.Workbooks.Open(Filename:=file)
' Если книга не пуста
If wkb.Sheets.Count > 0 Then
i = 1
ReDim v(1 To wkb.Sheets.Count)
' Получаем названия листов
For Each wks In wkb.Sheets
v(i) = wks.Name
i = i + 1
Next wks
End If
Cells(lRow, 3) = Join(v, ",")
wkb.Close False
DoEvents
lRow = lRow + 1
DoEvents
Next file
Set wks = Nothing: Set wkb = Nothing: Set EX = Nothing
Set colShts = Nothing
End Sub
Sub LoopThroughDirs()
Dim lLastRow As Long
Dim lRow As Long
Dim i As Long
Dim v As Variant
Dim dTime As Double
lRow = 2
lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
v = Range(Cells(2, 1), Cells(lLastRow, 2))
dTime = Time()
For i = LBound(v) To UBound(v)
Application.StatusBar = "Обрабатывается директория " & i & " из " & UBound(v)
Call LoopThroughFiles(v(i, 1), lRow, "*.xls")
Call LoopThroughFiles(v(i, 1), lRow, "*.xlsx")
Call LoopThroughFiles(v(i, 1), lRow, "*.xlsm")
DoEvents
Next i
MsgBox "Готово за " & CStr(CDate(Time() - dTime))
End Sub
/**
* Заменяет стандартное поле "Описание" полем с редактором WYSIWYG
* на странице правки категории
*
* @since 2.1.0
*
* @param object $term Current category term object.
*/
function pc_term_wysiwyg_description_field( $term ) {
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="description"><?php _e('Description'); ?></label></th>
<td>
<?php
$settings = array('wpautop' => true, 'media_buttons' => true, 'quicktags' => true, 'textarea_rows' => '15', 'textarea_name' => 'description' );
wp_editor(html_entity_decode($term->description), 'cat_description', $settings);
?>
<br />
<script>
jQuery(window).ready(function(){
jQuery( jQuery('label[for=description]')[0] ).parent().parent().remove();
//jQuery('#description').parent().parent().remove();
});
</script>
<style>#edittag{max-width:1100px;}</style>
<span class="description"><?php _e('The description is not prominent by default; however, some themes may show it.'); ?></span>
</td>
</tr>
<?php
}
// для категорий
add_action( 'product_cat_edit_form_fields', 'pc_term_wysiwyg_description_field', 10, 2 );
// для меток
add_action( 'product_tag_edit_form_fields', 'pc_term_wysiwyg_description_field', 10, 2 );
// для любых других таксономий по аналогии.
/**
* Получает список иерархических линий терминов для указанного или текущего поста в цикле.
*
* Возвращается ассоциативный массив вида id => строка id терминов разделенных символом "-" (минус)
*
* @param string $taxonomy Название таксономии
* @param integer/object [$post_id = 0] ID или объект поста
*
* @return array Массив id=>hi_line
*/
function get_unique_deep_term_ids( $taxonomy, $post_id = 0 ) {
if ( isset( $post_id->ID ) ) {
$post_id = $post_id->ID;
}
if ( ! $post_id ) {
$post_id = get_the_ID();
}
$terms = get_the_terms( $post_id, $taxonomy );
if ( ! $terms || is_wp_error( $terms ) ) {
return array();
}
$hierarchies = array();
foreach ( $terms as $term ) {
$ancestors = get_ancestors( $term->term_id, 'product_cat' );
array_unshift( $ancestors, $term->term_id );
$hierarchies[ $term->term_id ] = implode( '-', array_reverse( $ancestors ) );
}
arsort( $hierarchies, SORT_STRING );
$old = '';
$hierarchies = array_filter( $hierarchies, function ( $value ) use ( &$old ) {
$success = false === strpos( $old, $value );
$old = $value;
return $success;
} );
return $hierarchies;
}
/** @var WC_Product $product */
global $product;
$hi_lines = get_unique_deep_term_ids( 'product_cat', $product->get_id() );
foreach ( $hi_lines as $key => $value ) {
$hi_lines[ $key ] = get_term_parents_list( $key, 'product_cat', $args = array( 'separator' => ' / ' ) );
}
...
// Взято по аналогии из шаблона woocommerce/single-product/meta.php
<?php echo '<div class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . '<br>' . implode('<br>', $hi_lines) . '</div>' ?>
Public Function ToText(ByRef rng As Range) As String
ToText = rng.Text
End Function
woocommerce_checkout_order_processed