[WP/PHP] 直前のURLを確認して、リンクURLを変更する

<?phpfunction oc_get_back_link() { global $post; $back_link_url = "javascript:history.back();"; // 直前のURLをチェック同一ドメインからの遷移ならhistory.back()を返す $h = $_SERVER['HTTP_HOST']; if ( !empty($_SERVER['HTTP_REFERER']) && (strpos($_SERVER['HTTP_REFERER'],$h) !== false)) { return $back_link_url; } // 外部サイトからの遷移の場合は、トップページへのURLを返す $back_link_url = get_home_url(); return $back_link_url;}

[WP]qTranslate X Cleanup to single language

<?php// qTranslate X Cleanup to single language// 1: database backup [important!!!]// 2: settings -> language ->[Import/Export] -> [Convert database to the "square bracket only" style.]check -> SaveChanges// 3: this code paste to functions.php// 4: reload your site// 5: delete this code from functions.php// 6: Remove qTranslate pluginglobal $post;$language = 'en'; // Language you want to keep$args = array( 'post_type' => array('post','page'), // Change if necessary 'post_status' => array('publish','pending','draft','auto-draft','future','private','inherit','trash'), // Change if necessary 'posts_per_page' => 9999999, 'offset' => 0, 'orderby' => 'ID', 'order' => 'ASC', 'suppress_filters' => true, 's'=> '[:]');$posts_array = get_posts( $args );foreach ( $posts_array as $post ) : setup_postdata( $post ); $post->post_content = qtrans_use($language, $post->post_content,false); $post->post_title = qtrans_use($language, $post->post_title,false); wp_update_post($post); $count++;endforeach;wp_reset_postdata();

[WP] Google Analytics Dashboard for WP (GADWP) の認証が突然切断される場合の応急処置

<?php/** * functions.phpに書いてね */// Google Analytics Dashboard for WP (GADWP) 専用処理// トラッキングコードをテーマ側での出力するため、プラグインの処理は停止function oc_wp_loaded_gadwp() { if ( class_exists( 'GADWP_Tracking' ) && function_exists( 'GADWP' ) ) { $oc_gadwp_plugin = GADWP(); if ( isset($oc_gadwp_plugin->tracking) && isset($oc_gadwp_plugin->tracking->analytics) ) { // GoogleAnalyticsコード出力用のアクションのみを取り除く remove_action( 'wp_head', array( $oc_gadwp_plugin->tracking->analytics, 'output' ), 99 ); remove_action( 'wp_footer', array( $oc_gadwp_plugin->tracking->analytics, 'output' ), 99 ); } }}add_action('wp_loaded', 'oc_wp_loaded_gadwp', 99);// GoogleAnalyticsコードの出力function oc_google_analytics() { ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-1', 'auto'); ga('send', 'pageview'); </script><?php}add_action( 'wp_head', 'oc_google_analytics', 999 );

[WordPress] 指定日時以前・以後の処理を行うための判定方法

<?php // 終了日時の定義 $end_datetime = "2018/6/1 23:59:59"; // 現在日時のタイムスタンプ取得 $current_time = date_i18n("U"); // 終了日時のタイムスタンプ取得 $end_time = date_i18n("U",strtotime($end_datetime)); // デバッグ用 // echo $current_time . " " . $end_time . "<br>"; // echo date_i18n("Y-m-d H:i:s", $current_time) . "<br>"; // echo date_i18n("Y-m-d H:i:s", $end_time) . "<br>"; // echo $current_time < $end_time ? "in_range" : "out_range"; // 判定 if( $current_time < $end_time ) { // 終了日時より前の処理 } else { // 終了日時以降の処理 }

[CSS] クラスをワイルドカード指定する

<h2>.list-item-* だけ文字色を赤色にするCSS指定</h2><ul> <li class="list-item-a">.list-item-a</li> <li class="list-data-b">.list-data-b</li> <li class="list-item-c">.list-item-c</li> <li class="list-data-d">.list-data-d</li> <li class="list-item-e">.list-item-e</li> <li class="list-data-f">.list-data-f</li></ul><h2>複数クラスが指定されている場合の .list-item-* だけ文字色を青色にするCSS指定</h2><ul> <li class="list list-item-a">.list.list-item-a</li> <li class="list list-data-b">.list.list-data-b</li> <li class="list list-item-c">.list.list-item-c</li> <li class="list list-data-d">.list.list-data-d</li> <li class="list list-item-e">.list.list-item-e</li> <li class="list list-data-f">.list.list-data-f</li></ul>

[WordPress] 投稿・固定ページ・カスタムフィールドに紐づく画像を取得・表示するためのオレオレ関数

<?php/** * 投稿に紐づく画像を1点表示する */function oc_the_image($post_ID = 0, $size = "large", $attr = "", $icon = false, $custom_field_key = "image", $primary_img_id = "", $notfound_img = "notfound.png") { echo oc_get_the_image($post_ID, $size, $attr, $icon, $custom_field_key, $primary_img_id, $notfound_img);}/** * 投稿に紐づく画像のHTMLコードを取得する */function oc_get_the_image($post_ID = 0, $size = "large", $attr = "", $icon = false, $custom_field_key = "image", $primary_img_id = "", $notfound_img = "notfound.png") { $content = ""; $key = oc_get_pict_key($post_ID, $custom_field_key, $primary_img_id); $img = oc_get_pict_src($key, $size, $icon, $notfound_img); if($img) { $content = '<img src="'. $img[0] .'" width="' . $img[1] . '" height="' . $img[2] . '" ' . $attr . ' />'; } return $content;}/** * 投稿に紐づくカスタムフィールドに指定した画像を1点取得する * - カスタムフィールドには画像IDが格納されている前提での処理です。 */function oc_get_cf_img_url( $post_id, $custom_field_key ) { $imgid = get_post_meta($post_id,$custom_field_key,true); if($imgid) { $img = oc_get_pict_src($imgid, "full", false, "notfound.png"); if($img) { return $img[0]; } } return "";}/** * 投稿に紐づく画像IDを取得する */function oc_get_pict_key($post_ID = 0, $custom_field_key = "image", $primary_img_id = "") { // 投稿IDが0なら現在の投稿IDを使用する if($post_ID == 0) { global $post; $post_ID = $post->ID; } // ------------------------------------------------- // 優先表示画像を表示する // ------------------------------------------------- if ($primary_img_id != "") { $key = $primary_img_id; // ------------------------------------------------- // アイキャッチ画像があれば表示する // ------------------------------------------------- } elseif ( function_exists("has_post_thumbnail") && has_post_thumbnail($post_ID)) { $key = get_post_meta($post_ID, '_thumbnail_id', true); // ------------------------------------------------- // カスタムフィールドに登録された最初の画像を使う // ------------------------------------------------- } else { $key = get_post_meta($post_ID, $custom_field_key, true); } // ------------------------------------------------- // ココまでに画像IDが取得できなければ // 記事に登録された最初の画像を使う // ------------------------------------------------- if (empty($key) || $key == 0 ){ $args = array( 'post_parent' => $post_ID, 'post_type' => 'attachment', 'post_mime_type' => 'image'); $files = get_children($args); $img_src = ""; if (!empty($files)){ $keys = array_keys($files); $key = $keys[0]; // 最初の写真を使う } } return $key;}/** * 画像の情報(URL、幅、高さ)を取得する */function oc_get_pict_src($key, $size, $icon=false, $notfound_img = "notfound.png") { $img = array(); // 画像IDが取得されていれば画像を表示 if (!empty($key) && $key != 0 ){ $img = wp_get_attachment_image_src($key, $size, $icon); } else { // ------------------------------------------------- // デフォルト画像を使用する // ------------------------------------------------- // それでもなければ、NOT FOUND画像を使う $notfound_path = get_stylesheet_directory_uri()."/images/common/".$notfound_img; // ココは適宜書き換え $width = 100; $height = 100; global $_wp_additional_image_sizes; // 配列(縦、横)でサイズを指定された場合 if(is_array( $size ) && count( $size ) >= 2 ) { $width = $size[0]; $height = $size[1]; // 文字列('thumbnail'等)でサイズを指定された場合 } elseif (is_string($size) && !empty($size) && !empty($_wp_additional_image_sizes[$size]) ) { $tumb_size = $_wp_additional_image_sizes[$size]; $width = $tumb_size["width"]; $height = $tumb_size["height"]; // 該当なし } else { // 初期値のまま表示 } $img[0] = $notfound_path; $img[1] = $width; $img[2] = $height; } return $img; }

[CSS]テーブルの行に見出しセル(TH)が1つだけ存在する場合にだけ幅を設定する

<h2>見出しセルが一行に1つだけの時には見出しセル幅を固定する</h2><table> <tr> <th>見出し</th> <td>データ</td> </tr> <tr> <th>見出し</th> <td>データ</td> </tr> <tr> <th>見出し</th> <td>データ</td> </tr></table><h2>見出しセルが一行に複数ある場合には見出しセル幅を固定しない</h2><table> <tr> <th>見出し</th> <th>見出し</th> <th>見出し</th> </tr> <tr> <td>データ</td> <td>データ</td> <td>データ</td> </tr> <tr> <td>データ</td> <td>データ</td> <td>データ</td> </tr></table>

[WordPress]投稿日から●●日以内の記事にNEWマークを付けるためのチェック関数

<?php// NEWを表示する日数を指定define("NEWEST_POST_DAYS", 7); /** * 記事にNEWを付けるか判定する処理 */function is_newest_post($the_post) { // NEWを付加する日数 $days = NEWEST_POST_DAYS; // 記事投稿後の経過日数 $today = date_i18n('U'); $posted = get_the_time('U',$the_post->ID); $elapsed = date('U',($today - $posted)) / (60*60*24) ; // NEWを付加する日数よりも経過日が小さければtrueを返す if( $days > $elapsed ){ return true; } else { return false; }}

[jQuery]手軽に実装する上に戻るボタン。最初は非表示である程度スクロールすると表示される機能付き。

$(document).ready(function(){ $(window).scroll(function() { if($(this).scrollTop() > 100) { // 100pxスクロールしていたら上に戻るボタンを表示 $(".back-to-top").fadeIn(); } else { $(".back-to-top").fadeOut(); } }); $(".back-to-top").click(function() { $("body,html").animate({scrollTop:0},800); // 800msかけて上に戻る });});

[CSS]背景画像をアニメーションすることで簡単に作れる無限ループスライドショー

<div class="bg-image-loop"></div>.bg-image-loop { width: 100%; height: 160px; /* 画像の高さを指定 */ position: relative; background: url("//onocom.net/code/wp-content/uploads/2018/01/loop_bg.png") repeat-x 0 0; background-size: auto 100%; animation: bg-slider 23s linear infinite; /* 23sの部分背景画像の約数だとスムーズ */ margin: 80px 0; padding: 0;}@keyframes bg-slider { from { background-position: 0 0; } to { background-position: -1518px 0; } /* 1518pxとは使用した背景画像の長さ */}

[CSS]下にスクロールしろという案内をふわふわアニメートするCSS

<p class="scroll-announce">下にスクロールしてね</p>body { background: #000; color: #fff; min-height: 1000px;}.scroll-announce { text-align: center; position: relative;}.scroll-announce:after { font-size: 40px; font-weight: bold; display: block; text-align: center; content: "↓"; position: absolute; left: 50%; left: calc( 50% - 24px ); bottom: -100px; width: 48px; animation: scroll-announce 3s ease infinite;}@keyframes scroll-announce { 0% { transform:translateY(0) } 70% { transform:translateY(-15px) } 100% { transform:translateY(0) }}

[Bootstrap]ナビゲーションをAffixさせる際にスライドインする処理

<div class="navbar" data-spy="affix" data-offset-top="60"> Header Navigation</div><div class="empty-field"></div>.navbar { background: #000; color: #fff; padding: 15px 0; text-align: center;}.navbar.affix-top { position: static; top: -120px;}.navbar.affix { position: fixed; top: 0px; width: 100%; -webkit-transition: all 1s ease-in-out; transition: all 1s ease-in-out; opacity: 0.95;}body { /* Affixをわかりやすくするためにグラデーションつける */ background-color: #F07575; /* fallback color if gradients are not supported */ background-image: linear-gradient(to bottom, hsl(0, 80%, 70%), #bada55); /* Standard syntax; must be last */}.empty-field { height: 1000px;}

WordPressのカテゴリー・タクソノミー等のアーカイブページの接頭辞を削除する

<?phpadd_filter( 'get_the_archive_title', function ($title) { if ( is_category() ) { /* translators: Category archive title. 1: Category name */ $title = sprintf( __( '%s' ), single_cat_title( '', false ) ); } elseif ( is_tag() ) { /* translators: Tag archive title. 1: Tag name */ $title = sprintf( __( '%s' ), single_tag_title( '', false ) ); } elseif ( is_author() ) { /* translators: Author archive title. 1: Author name */ $title = sprintf( __( '%s' ), '<span class="vcard">' . get_the_author() . '</span>' ); } elseif ( is_year() ) { /* translators: Yearly archive title. 1: Year */ $title = sprintf( __( '%s' ), get_the_date( _x( 'Y', 'yearly archives date format' ) ) ); } elseif ( is_month() ) { /* translators: Monthly archive title. 1: Month name and year */ $title = sprintf( __( '%s' ), get_the_date( _x( 'F Y', 'monthly archives date format' ) ) ); } elseif ( is_day() ) { /* translators: Daily archive title. 1: Date */ $title = sprintf( __( '%s' ), get_the_date( _x( 'F j, Y', 'daily archives date format' ) ) ); } elseif ( is_tax( 'post_format' ) ) { if ( is_tax( 'post_format', 'post-format-aside' ) ) { $title = _x( 'Asides', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) { $title = _x( 'Galleries', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-image' ) ) { $title = _x( 'Images', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-video' ) ) { $title = _x( 'Videos', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-quote' ) ) { $title = _x( 'Quotes', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-link' ) ) { $title = _x( 'Links', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-status' ) ) { $title = _x( 'Statuses', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-audio' ) ) { $title = _x( 'Audio', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-chat' ) ) { $title = _x( 'Chats', 'post format archive title' ); } } elseif ( is_post_type_archive() ) { /* translators: Post type archive title. 1: Post type name */ $title = sprintf( __( '%s' ), post_type_archive_title( '', false ) ); } elseif ( is_tax() ) { $tax = get_taxonomy( get_queried_object()->taxonomy ); /* translators: Taxonomy term archive title. 1: Taxonomy singular name, 2: Current taxonomy term */ $title = sprintf( __( '%2$s' ), $tax->labels->singular_name, single_term_title( '', false ) ); } else { $title = __( 'Archives' ); } return $title;});

ボックスの左上に三角形の新着(NEW表示)を表示するCSS

.mark-box { width: 200px; height: 200px; position: relative; padding: 30px; background-color: #fef2f2;}.mark-box:before { position: absolute; content: ""; left: 0; top: 0; width: 0; height: 0; border-style: solid; border-width: 50px 50px 0 0; border-color: #f00 transparent transparent transparent;}.mark-box:after { position: absolute; content: "NEW"; transform: rotate(315deg); display: block; font-size: 11px; white-space: pre; color: #fff; top: 12px; left: 4px; text-align: center; z-index: 2; line-height: 1.2;}

Beaver Builderでカスタムカラーを設定する

<?php// functions.phpに定義する// ---------------------------------------------------------------------------// ページビルダー用カラープリセットの定義// ---------------------------------------------------------------------------function oc_builder_color_presets( $colors ) { $colors[] = '7BA964'; $colors[] = '1CAFE4'; $colors[] = 'FA573D'; return $colors;}add_filter( 'fl_builder_color_presets', 'oc_builder_color_presets' );