Wonderful! WordPress

良く使いそうなのに忘れやすい些細なこと

Page No.1

WordPress のテーマやプラグイン自作など、といってもWordPress 以外の事でも使えることももちろんありますが、phpjavascriptjQueryで良く使いそうなことなのにすぐに忘れてしまう些細な事などを色々と。

《 Related WordPress 》

WordPress において、スタイルシートやjavascript などのスクリプトを登録するための記述。
WordPress のheader.phpにおいてのスタイルシート、htmlにおいて、

<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/single_nr.css<?php echo '?ver='.date('YmdHis',filemtime(get_stylesheet_directory().'/single_nr.css')); ?>" media="screen and (max-width: 768px)" />
PHP
CopyExpand

WordPress のheader.phpにおいてのスタイルシート、phpでは、

<?php
	wp_enqueue_style('si_nr_style',get_template_directory_uri().'/style_nr.css',false,date('YmdHis',filemtime(get_stylesheet_directory().'/style_nr.css')),'screen and (max-width: 770px)');
	wp_head();
?>
PHP
CopyExpand

WordPress のfooter.php等においてのスクリプト、phpでは、

<?php
	wp_enqueue_script('assist_jq',get_template_directory_uri().'/assist_jq.js',array('jquery'),date('YmdHis',filemtime(get_stylesheet_directory().'/assist_jq.js')),true);
	wp_footer();
?>
PHP
CopyExpand

WordPress のプラグイン等においてphpでは、

<?php
	function direct_flyjpf_jq() {
		wp_enqueue_style( 'flying_jpf_style', plugins_url( 'flying_jpf.css', __FILE__ ), false, date( 'YmdHis', filemtime(plugin_dir_path( __FILE__ ).'flying_jpf.css' )), 'screen and (min-width: 770px)' );
		wp_enqueue_script( 'flyjpf_jq',plugins_url( 'flyjpf_jq.js', __FILE__ ), array( 'jquery' ), date( 'YmdHis', filemtime(plugin_dir_path( __FILE__ ).'flyjpf_jq.js' )),true);
	}
	
	add_action( 'wp_enqueue_scripts', 'direct_flyjpf_jq' );
?>
PHP
CopyExpand

よく使うことになるいろいろなパスを得る関数

<?php
	function template_pass( $tar = '' ) {
		$curpass = '';
		if ( 'fullpass' === $tar ) {
	
			// /var/www/html/example/wp-content/themes/twentyten/等のテーマディレクトリのフルパス
			$curpass = get_template_directory() . '/';
		} elseif ( 'uppass' === $tar ) {
	
			// /var/www/html/example/wp-content/uploads/等のアップロードディレクトリのフルパス
			$upload_dir = wp_upload_dir();
			$curpass = $upload_dir['basedir'] . '/';
		 } elseif ( 'upurl' === $tar ) {
	
			// https://localhost/example/wp-content/uploads/2016/07/等のアップロードディレクトリのurl
			$upload_dir = wp_upload_dir();
			$curpass = $upload_dir['url'];
			$curpass = substr( $curpass, 0, strpos( $curpass, 'uploads' ) + 8 );
		} elseif ( 'content' === $tar ) {
	
			// /var/www/html/example/wp-content/等のwp-contentディレクトリのフルパス
			$curpass = WP_CONTENT_DIR . '/';
		} else {
	
			// テーマフォルダのルートからの相対パスをかえす。./wp-content/themes/sanbanze/
			$curhome =  home_url();
			$curfolder = get_template_directory_uri();
			$curpass = str_replace( $curhome, '.', $curfolder ) . '/';
		}
		return $curpass;
	}
?>
PHP
CopyExpand

《 php 》

フルパスを調べる

$_SERVER['DOCUMENT_ROOT'] もしくは $_SERVER['SCRIPT_FILENAME'] で取得できる。

var_dump の代わりの foreach 再起関数

どうも var_dump がわかりづらくて・・・。
いずれ作ろうと思ってたもの。

<?php
    function echo_array( $ary, $ope = 1, $k = '' ) {
        $arw = '▸';// '▹';

        if ( is_array( $ary ) ) {

            foreach ( $ary as $key => $val) {
                
                if ( is_array( $val ) ) {
                    if ( $ope ) {
                        $tk = is_numeric( $key ) ? '[' . ( string )$key . ']' : '[\'' . $key . '\']';

                        $tmpk = $k . $tk;
                    } else {
                        $tmpk = ( string )$k . ( '' !== $k ? $arw : '' ) . ( string )$key;
                    }
                    echo_array( $val, $ope, $tmpk );

                } else {
                    if ( $ope ) {
                        $tk = is_numeric( $key ) ? '[' . ( string )$key . ']' : '[\'' . $key . '\']';

                        echo '<p>' . $k . $tk . $arw . $val . '</p>';
                    } else {
                        echo '<p>' . $k . ( '' !== $k ? $arw : '' ) . $key . $arw . $val . '</p>';
                    }
                }
            }
        } else {
            echo '<p>' . $k . ( $k ? $arw : '') . $ary . '</p>'; 
        }
    }

    echo_array( $metadata );
?>

PHP
CopyExpand

それにしても再帰呼び出しというのはこんがらがる。つるつる脳みそがよけいウニになる。
こんな具合で良いんじゃないかと思うのだけれども、きっと、もっと簡単にかけるに違いない。
んで、下のような感じに表示される。
これは WordPress においてデータベースに保存されている画像のメタデータ。get_metadata() で取得でき、これ一発で必要な画像データはほぼ得られる。なお、この場合のメタデータのキーは、'_wp_attachment_metadata'。

<?php
  // この場合の$post->ID は画像を貼り付けた投稿ではなく、画像自体が登録してある行のID
  $metadata = get_metadata( 'post', $post->ID, '_wp_attachment_metadata' );
?>

[0]['width']▸1300
[0]['height']▸750
[0]['file']▸2016/04/1603120634_xwing.jpg
[0]['sizes']['thumbnail']['file']▸1603120634_xwing-150x150.jpg
[0]['sizes']['thumbnail']['width']▸150
[0]['sizes']['thumbnail']['height']▸150
[0]['sizes']['thumbnail']['mime-type']▸image/jpeg
[0]['sizes']['medium']['file']▸1603120634_xwing-500x288.jpg
[0]['sizes']['medium']['width']▸500
[0]['sizes']['medium']['height']▸288
[0]['sizes']['medium']['mime-type']▸image/jpeg
[0]['sizes']['medium_large']['file']▸1603120634_xwing-768x443.jpg
[0]['sizes']['medium_large']['width']▸768
[0]['sizes']['medium_large']['height']▸443
[0]['sizes']['medium_large']['mime-type']▸image/jpeg
[0]['image_meta']['aperture']▸0
[0]['image_meta']['credit']▸
[0]['image_meta']['camera']▸
[0]['image_meta']['caption']▸
[0]['image_meta']['created_timestamp']▸0
[0]['image_meta']['copyright']▸
[0]['image_meta']['focal_length']▸0
[0]['image_meta']['iso']▸0
[0]['image_meta']['shutter_speed']▸0
[0]['image_meta']['title']▸
[0]['image_meta']['orientation']▸0
PHP
CopyExpand

多次元配列用 implode 代替 foreach 再起関数

早い話、なんてことはなく、上の var_dump の代替の再起関数を値だけのシンプルなものにしただけのもの。

<?php
    function multi_implode( $separater = ' ', $target = array() ) {
        $resstr = array();

        if ( is_array( $target ) ) {
            foreach ( $target as $val ) {
                if ( is_array( $val ) ) {
                    $resstr[] = multi_implode( $separater, $val );
                } else {
                    $resstr[] = $val;
                }
            }
        }
        return implode( $separater, $resstr );
    }
?>
PHP
CopyExpand

可変変数

変数の値を変数の名前として利用する。
対象として使用する変数の名前を可変(動的)にできる。
基本的に $$ というように $ を続けて書けばいいのだけれど、ちょっと注意が必要なのは配列の要素としての文字列を変数名として指定する場合。 例えばこんな感じ。

<?php
    $jap = array( '日', '月', '火', '水', '木', '金', '土', '日' );
    $eng = array( 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su' );
    $ope = array( 'jap', 'eng' );
    $tar = array();
    for ( $i = 0 ; $i < 2; ++$i ) {
        $tar = ${ $ope[$i] };
        // $tar = $$ope[$i]; -> これでは error となる

        foreach ( $tar as $val ) {
            echo '<p>' , $val , '</p>';
        }
        $tmp = $ope[ $i ];
        echo '<p>Tuesday : ' , $$tmp[2] , '</p>';
        // もしくは一行でかくなら
        echo '<p>Wednesday : ' , ${ $ope[ $i ] }[3] , '</p>';
    }
?>
PHP
CopyExpand

関数内関数

<?php
    // 新たにページ番号を設定した url query を返す関数
    function ret_query( $page = 0 ) {

        // parse_str は url query を & でバラした後個々の値をキーとする連想配列にしてくれる
        parse_str( $_SERVER['QUERY_STRING'], $queries );

        // 親の変数 $queries は子関数からは見えないので引数として渡す
        function retpaged( $num = 0, $q ) {

            if ( $num < 1 ) {
                unset( $q['paged'] );
            } else {
                $q['paged'] = $num;
            }
            $retstr = '';

            foreach ( $q as $key => $val ) {
                $retstr .= $key . '=' . $val . '&';
            }
            return trim( $retstr, '&' );
        };
        return retpaged( $page, $queries );
    }
?>

PHP
CopyExpand

関数内クロージャ

<?php
    function ret_query( $page = 0 ) {

        parse_str( $_SERVER['QUERY_STRING'], $queries );

        // 親の変数 $queries は子関数(クロージャ)からは見えないので use で見えるようにする、
        // &$ にすれば参照渡しになって $queries の変更がリアルになる
        $retpaged = function ( $num = 0 ) use ( $queries ) {

            if ( $num < 1 ) {
                unset( $queries['paged'] );
            } else {
                $queries['paged'] = $num;
            }
            $retstr = '';

            foreach ( $queries as $key => $val ) {
                $retstr .= $key . '=' . $val . '&';
            }
            return trim( $retstr, '&' );
        };
        return $retpaged( $page );
    }
?>

PHP
CopyExpand

呼ばれた先を知ることができる debug_backtrace()

<?php
		$error_log = './phperror.log';
        if ( file_exists( $error_log ) ) {
            $erlist = file ( $error_log );
        } else {
            $erlist = array();
        }
        $cdt = date( 'Y/m/d H:i:s' );

        // debug_backtrace()
        // その関数が呼ばれた先を辿って知ることができる関数
        // 呼ばれた道筋の配列で返され、それぞれがまた内容を示す連想配列となっている
        // function : string : カレントの関数名。 
        // line : int : カレントの行番号。
        // file : string : カレントのファイル名。
        // class : string : カレントのクラス名。 
        // object : object : カレントのオブジェクト。 
        // type : string : カレントのコール方式。メソッド呼び出しの場合は "->"、 静的なメソッド呼び出しの場合は "::" が返される。 関数呼び出しの場合は何も返されない。 
        // args : array : 関数の内部の場合、関数の引数のリスト
		$dbg = debug_backtrace();
		$dbgs = '';
		foreach ( $dbg as $dbgrow ) {
			$tmpdbg = $dbgrow['file'] . '>' . $dbgrow['function'] . '>' . $dbgrow['line'];
			$dbgs .= '=>' . $tmpdbg;
		}

		$erlist[] = '[' . $cdt . ']' . $dbgs . "\n";
		file_put_contents ( $error_log, $erlist, LOCK_EX );
?>

PHP
CopyExpand

で、結果はこんな感じになる。

[2021/08/10 07:57:28]=>
C:\Apache24\htdocs\wp\wp-includes\formatting.php>wp_check_invalid_utf8>4519=>C:\Apache24\htdocs\wp\wp-content\plugins\simplistic_pagenavi\simplistic_pagenavi.php>esc_attr>214=>C:\Apache24\htdocs\wp\wp-content\plugins\simplistic_pagenavi\simplistic_pagenavi.php>get_url_parameter>121=>C:\Apache24\htdocs\wp\wp-content\plugins\simplistic_pagenavi\simplistic_pagenavi.php>load_option>51=>C:\Apache24\htdocs\wp\wp-content\plugins\simplistic_pagenavi\simplistic_pagenavi.php>__construct>656=>C:\Apache24\htdocs\wp\wp-settings.php>include_once>409=>C:\Apache24\htdocs\wp\wp-config.php>require_once>107=>C:\Apache24\htdocs\wp\wp-load.php>require_once>50=>C:\Apache24\htdocs\wp\wp-blog-header.php>require_once>13=>C:\Apache24\htdocs\wp\index.php>require>17

PHP
CopyExpand

これって結構、便利! filter_var()

たとえば文字列の中から数字だけを拾い出してくれるとか
第二引数で指定できるフィルタには検証用とか下のような除去用とかいろいろなものがあり
ここね -> 「php.net フィルタの型」

<?php
    $x = '?page_id=24651';
    echo '<p>' . filter_var( $x, FILTER_SANITIZE_NUMBER_INT ) . '</p>';
    // 24651 
?>
PHP
CopyExpand

超ーっ!基本的なこと

たとえば、以下において・・・

<?php
	$var = array( 0, '0', '', null, array() );
	foreach ( $var as $val ) {
		if ( $val ) {
			echo '<p>true</p>';
		} else {
			echo '<p>false</p>';
		}
	}
?>
PHP
CopyExpand
if ( $val )
  • 0 => false
  • '0' => false ・・・ ※注意! js だとこれが true
  • '' => false
  • null => false
  • array() => false ・・・ ※注意! js だとこれも true
if ( '' == $val )
  • 0 => true
  • '0' => false
  • '' => true
  • null => true ・・・ ※ js だと false
  • array() => false ・・・ ※ js だと true
if ( '' === $val ) ・・・これは当然の事で忘れようがない・・・
  • 0 => false
  • '0' => false
  • '' => true
  • null => false
  • array() => false
if ( isset( $val ) ) ・・・これも当然であって間違いようがない・・・
  • 0 => true
  • '0' => true
  • '' => true
  • null => false
  • array() => true
if ( is_null( $val ) ) ・・・これもだけど・・・
  • 0 => false
  • '0' => false
  • '' => false
  • null => true
  • array() => false
if ( count( $val ) ) ・・・そしてこんなこともしてみると・・・
  • 0 => true count => 1
  • '0' => true count => 1
  • '' => true count => 1
  • null => false count => 0
  • array() => false count => 0

よくわかってるはずなのについうっかりやってしまう・・・

  • if ( strpos( $target, '*' ) ) ・・・strpos の場合はこれをやってはいけない。先頭に対象がある場合の戻り値は0であるから。
  • if ( false !== strpos( $target, '*' ) ) ・・・こうすること、常識。

《 CSS 》

cssにおいて改行させる。

.target:after{
	content:"\A";
	white-space:pre;
}
CSS
CopyExpand

メディアクエリ

@media screen and (min-width:470px){
	#content{
		padding-top:70px;
	}
}
CSS
CopyExpand

シャドウ、角丸

#target{
	border-radius: 5px;
	text-shadow:2px 2px 2px #F2F3A9,4px 4px 4px #000;
	box-shadow:0px 0px 5px 3px rgba(170,170,170,0.9) inset,3px 3px 5px 3px rgba(0,0,0,0.9);
}
	/*縦 横 ぼかし 広がり、最後にinsetを付加すると内側のシャドウ*/
	/*シャドウは複数指定可*/
CSS
CopyExpand

徐々に変わる文字色

#target{
	color:#ffffff;
	transition: color 0.3s;
}

#target:hover{
	cursor:pointer;
	color:#E6537D;
}
CSS
CopyExpand

animation のkeyframes 設定

#content{
	opacity:1;
	animation-name: fadein;
	animation-duration: 2.0s;
	/*アニメーション開始前の状態をkeyframes で指定してある最初の設定の状態にする場合はbackwards*/
	/*keyframes で指定してある最後の設定をそのまま引き継がせる場合はforwards*/
	/*両方とも適応させる場合はboth*/
	animation-fill-mode:both;
	animation-iteration-count: infinite;
	animation-timing-function: linear;
	/* animation-timing-function: steps( 1, end );*/
	animation-direction: normal;
	animation-delay:1.0s;
}

@keyframes fadein{
    from{ opacity: 0; }
    to{ opacity: 1;  }
}
CSS
CopyExpand

基本的なflex 設定

.posts{
	display:flex;
	/*行を複数にしない場合nowrap*/
	flex-wrap:wrap;
	justify-content:center;
}
CSS
CopyExpand

Leave a Reply!

JavaScript is necessary to send a comment.
You can edit and delete your comment if you input a edit key.
Edit key is necessary for attesting you when you edit and delete it.
The tag of HTML cannot be used in comment.
When you comment for the first time, it is displayed after the approval of the administrator.
Because I cannot speak English so much, it takes time to answer.
Required fields are marked *.

※Please enter more than 5 characters only alphabets.
※Edit or delete are possible for 2000 days after approval.

*

♠Simplistic Comment User Editable v4.0

♠When visitors leave comments on the site this site collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection.
♠This site does not use cookie when visitors leave comments and commenter edit comment.
♠This site uses Akismet to reduce spam. Learn how your comment data is processed.

Comments feed

Trackback URL : https://strix.main.jp/wp-trackback.php?p=59466

Sanbanse Funabashi
2011.01.01 sunrise

Top

スクロールさせるか画像をクリックすると元に戻ります。