タイトル・抜粋・カスタムフィールド等の文字数を指定して取得する関数です。
ソースコード
functions.php
<?php
/**
* @function get_trim_str
* @param str(string), len(int), suffix(string), echo(bool)
* @return string
*/
if(!function_exists('get_trim_str')){
function get_trim_str($args = ''){
$defaults = array(
'str' => '',
'len' => 30,
'suffix' => '..',
'echo' => true
);
$args = wp_parse_args($args, $defaults);
extract($args, EXTR_SKIP);
$str = esc_html($str);
$len = intval($len);
$suffix = esc_html($suffix);
if(mb_strlen($str, 'UTF-8') > $len){
$output = mb_substr($str, 0, $len, 'UTF-8').$suffix;
}else{
$output = $str;
}
if($echo){
echo $output;
}else{
return $output;
}
}
}
?>
パラメータ
str(取り出したい文字列を含む文字列)
len(取り出す文字数を指定)
- 30(正数)初期値
suffix(接尾辞)
- ..(文字列)初期値
echo (出力)
- 1(true)初期値
- 2(false)
使用例
抜粋の文字数を指定して表示したい場合
ソース
<?php get_trim_str(array('str'=>get_the_excerpt(), 'len'=>100)); ?>