[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 { // 終了日時以降の処理 }

[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; }

[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; }}

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;});

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' );

[WordPress] カスタムフィールドの値を元に特定のページでリダイレクトする方法

<?php/** * 外部リンクページのリダイレクト処理 */function oc_template_redirect() { if ( is_page() ) { $status = 302; $location = ""; $post_id = get_queried_object_id(); // 外部サイトへリダイレクトするためのカスタムフィールドを取得 $location = get_post_meta($post_id, "oc_external_link_url", true); // 空でなければリダイレクト(状況によってはURLの文字列チェック等がいるかも) if(!empty($location) ) { wp_redirect( $location, $status ); exit; } }}add_action( 'template_redirect', 'oc_template_redirect' );

[WordPress] 新着情報表示用ショートコード

<?php/** * お知らせショートコード * 使用例: [topics_list count=10 cat_slug="news" ] */function oc_topics_list( $atts ) { $settings = shortcode_atts( array( 'cat_slug' => '', 'count' => 10, 'post_type' => 'post', ), $atts ); $html = ""; $args = array( 'posts_per_page' => $settings["count"], 'orderby' => 'date', 'order' => 'desc', 'post_type' => $settings["post_type"], 'post_status' => 'publish' ); if( !empty($settings["cat_slug"]) ) { $args["category_name"] = $settings["cat_slug"]; } $topics = get_posts( $args ); foreach($topics as $topic) { $date = get_the_time("Y年m月d日",$topic); $cats = get_the_category($topic->ID); $url = get_permalink($topic); $title = get_the_title($topic); $html .= "<li> <span class='date'>{$date}</span> <span class='content'><a href='{$url}'>{$title}</a></span> </li>"; } return "<ul class='topics-list'>{$html}</ul>";}add_shortcode( 'topics_list', 'oc_topics_list' );

WordPressのプラグインで、get_template_part的なものを使いたい

<?php// wp-content/plugins/wp-onocom-plugin.php class wp_onocom_plugin { static $instance = null; function __construct(){ self::$instance = $this; } public static function get_instance() { if( self::$instance != null ) { return self::$instance; } else { return new self(); } } public function get_plugin_template_part($slug, $name = null) { $templates = array(); $name = (string) $name; if ( '' !== $name ) $templates[] = "{$slug}-{$name}.php"; $templates[] = "{$slug}.php"; $located = ''; foreach ( (array) $templates as $template_name ) { if ( !$template_name ) { continue; } if ( file_exists($this->get_plugin_path() . '/' . $template_name) ) { $located = $this->get_plugin_path() . '/' . $template_name; break; } } if($located) { require_once( $located ); } } public function get_plugin_url() { return plugins_url("",__FILE__); } public function get_plugin_path() { return dirname(__FILE__); }}

WordPress TinyMCEのスタイルメニューの項目追加

<?phpif ( !function_exists( 'initialize_tinymce_styles' ) ):add_filter('tiny_mce_before_init', 'initialize_tinymce_styles', 10000);function initialize_tinymce_styles($init_array) { $style_formats = array( array( 'title' => '否定', 'inline' => 'span', 'classes' => 'text-negative' ), array( 'title' => '肯定', 'inline' => 'span', 'classes' => 'text-positive' ), array( 'title' => '例示・用語', 'inline' => 'span', 'classes' => 'text-example' ), array( 'title' => '強調', 'inline' => 'strong', 'classes' => 'text-emphasis' ), array( 'title' => '区切り線', 'block' => 'hr', 'classes' => 'hr-divider' ), ); $init_array['style_formats'] = json_encode($style_formats); return $init_array;}endif;

WordPress/PHP 投稿IDを元に固有のCSSグラデーションを生成するコード

<?phpfunction onocom_code_gradient( $post_id = false ) { global $post; if( $post_id == false ) { $post_id = $post->ID; } // 投稿日時のUnix Epoch (1970 年 1 月 1 日 0 時 0 分 0 秒) からの秒数から係数を求める $seed = ( get_the_time("U",$post_id) * $post_id ); $seed = '0.' . substr($seed,-5,5); if($seed < 0.5){ $seed *= 2; } $start = sprintf("#%06x", 0xcccccc * $seed ); $end = sprintf("#%06x", 0xFFFFFF * $seed );?><style>/* セレクタは適宜変更すること */.single #post-<?php echo $post_id; ?> .entry-header { background: <?php echo $start;?>; background: -webkit-linear-gradient(to right, <?php echo $start;?>, <?php echo $end;?>); background: linear-gradient(to right, <?php echo $start;?>, <?php echo $end;?>);</style><?php}

WordPressのfunctions.phpでまとめてタクソノミー登録

<?phpadd_action('init', 'onocom_custom_taxonomies');function onocom_custom_taxonomies() { $post_type = 'item'; $taxonomies = array( "taxslug-a" => "タクソノミーA", "taxslug-b" => "タクソノミーB", "taxslug-c" => "タクソノミーC", "taxslug-d" => "タクソノミーD", "taxslug-e" => "タクソノミーE", "taxslug-f" => "タクソノミーF", ); foreach ($taxonomies as $key => $label) : $labels = array( 'hierarchical' => true, 'label' => $label, 'query_var' => true ); register_taxonomy( $key, $post_type, $labels ); endforeach;}?>