2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【WP-Champloo】文字数を指定して取得する関数

Last updated at Posted at 2013-04-05

タイトル・抜粋・カスタムフィールド等の文字数を指定して取得する関数です。

ソースコード

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)); ?>
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?