A Summary of Custom Code Changes in WordPress

English

To ensure I can quickly restore my customizations whenever I update my theme, I've put together a summary of my previous blog posts noting where and how I modified the WordPress code.

With this in mind, I went ahead with the workflow of updating the theme and then restoring my changes. After carefully testing everything in a local environment, I applied the fixes to the live site. Even when just copy-pasting, it's easy to panic if something breaks and the page won't load, so caution is key. While my local tests went off without a hitch, on the live site I ran into a few hiccups—like the initial forward slash "/" in a comment ("//") failing to copy over, or accidental full-width characters preventing "true" from working properly—which led to a few failed attempts.

Past Article Links

Here is a list of previous articles covering code modifications:

--------

Modification Details

Restricting "Previous" and "Next" posts to the same category only

wp-content/themes/lightning/_g3/template-parts/next-prev.php

<?php
global $bootstrap;
//$in_same_term   = apply_filters( 'lightning_prev_next_post_in_same_term', false );
$in_same_term   = apply_filters( 'lightning_prev_next_post_in_same_term', true ); //ここかな?
$excluded_terms = apply_filters( 'lightning_prev_next_post_excluded_terms', '' );
$taxonomy       = apply_filters( 'lightning_prev_next_post_taxonomy', 'category' );
?>

In the third line from the top, change the $in_same_term argument definition for get_previous_post() and get_next_post() from false to true.

Displaying only posts from the same category in the "Recent Posts" section of single post pages

wordpress/wp-content/themes/lightning/_g3/template-parts/sidebar-contents-post.php

//same categoryのため新規変数を追加する
$cats   = get_the_category(); //categoryは配列で入る
$cat_id = $cats[0]->term_id;  //一つ目のcategory ID

$post_loop = new WP_Query(
	array(
		'post_type'              => 'post',
	        'cat'                    => $cat_id,//add for restruct same category
		'posts_per_page'         => 10,
		'no_found_rows'          => true,
		'update_post_meta_cache' => false,
		'update_post_term_cache' => false,
	)
);
?>

Displaying the category feature image at the top of category pages

The past article structure is a bit complex, but it consists of:

Overview

  • Use the "Category Images" plugin to enable registering images for each category.
  • Modify the code to display the registered images on the category top pages.

Code Modifications

Modification Location 1

wordpress/wp-content/themes/lightning/_g3/template-parts/page-header.php
Add the following code to the very bottom.

The added code, with the original code highlighted in blue.

<!-- //カテゴリー独立プロジェクトのための修正、プラグインのCategory Imagesを利用している
<!-- //categoryだったらの条件はz_taxonomy_image()に入っていたのでそこもいじる -->
<?php
if (function_exists('z_taxonomy_image')){
  echo '<div style="text-align: center;">';
  echo '<div style="position: relative; display:inline-block;">';
  $taximage = z_taxonomy_image(); //これで画像[show]のecho、成功時にもhtmlコードを返すようにした
  if(!empty($taximage)){           //画像があったらカテゴリー名を[show]
    echo '<div style="position: absolute; top: 50%; left: 50%; max-width: 100%; max-height: 100%; color:white;transform:translate(-50%,-50%)">';
    echo '<p>';
    echo wp_kses( apply_filters( 'lightning_page_header_title_html', $page_header_title_html ), $allowed_html ); //カテゴリー名
    echo '</p>';
    echo '</div>';
  }
  echo '</div>';
  echo '</div>';
 }
?>

<!-- //edit 青い枠 -->
<?php
if (empty($taximage)){ //画像がなかったらこれまで通りの青い枠+文字
  echo '<div class="page-header"><div class="page-header-inner container">';
  echo wp_kses( apply_filters( 'lightning_page_header_title_html', $page_header_title_html ), $allowed_html );
  echo ('</div></div>');
 }
?>

<!-- [ /.page-header ] -->
Modification Location 2

Modify the code for the Category Images plugin. Since this is separate from the theme, it won't be overwritten by theme updates. However, if it gets overwritten during a plugin update, re-apply the fix as before.

I want to check whether an image exists using z_taxonomy_image(). I've configured it to always return $taxonomy_image, allowing me to check if it's missing using "if (empty($taximage))".


wordpress/wp-content/plugins/categories-images/categories-images.php
The function is zTaxonomyImage(). Comment out the sections highlighted in red.


        if ($echo)    echo $taxonomy_image;
        //else //edit 画像があったかどうかを判定したい
	return $taxonomy_image;
    }

Modifications to functions.php

Shortening the WordPress Archive List

Add the get_archives_link() filter code to wordpress/wp-content/themes/function.php

/* ウィジェットで[show]されるアーカイブを短く[show]させます
 * 1.リンクが/サイトurl/2022/07というように固定される。リンクは設定次第で変わるので、リンクはそのまま使いたい。 →解決
 * 2.月や週や日で指定された場合の考慮がない →解決
 * 3.12月に記事がない年は年[show]がされない →解決
 * 4.今月記事を書いてないと年[show]がされない →解決
 * 5.今年の記事しかなく、今月の記事がない場合、2回アーカイブを呼ばれると年が[show]されない。→未解決
 * 月[show]の後不要なhtmlタグが出ている「</a></li>」 →解決
 * もうガンガン作り変えます
 */
function my_archives_link($link_html){
    $currentMonth = date('n');
    $currentYear = date('Y');

//年指定の場合は何もしない
    if(strpos($link_html,'月') != true){
      return $link_html;
    }

//年/月/(日でもOK?)の場合
    // アーカイブの年月HTMLを編集
    $ym = explode('年', $link_html);        //ym[0]=<li><a href='https://localhost/?m=202206'>2022 ym[1]=6月</a></li> 
    $monthArray = explode('月', $ym[1]);    //$monthArray[0]=6 [1]=</a></li>
    $month = $monthArray[0];                //=6
    $year = intval(strip_tags($ym[0]));	    //2022 remove php html tags
    //$linkMonth = substr('0'.$month, -2);    //0+月の後ろ2文字 012 → 12, 07→07、2桁にしている いらない

    //リンク先
    preg_match_all('/'.+?'/', $ym[0], $urlArray);//正規表現で''で囲まれたURLを抽出
    $url = $urlArray[0][0];
    //echo '$urlEX =';echo $url;var_dump ($linkMonthArray); //for debug
	   
    $linkMonth  = '<a href='.$url.' style="white-space: nowrap;">'.$month.'月&nbsp;</a>';
    $linkYear   = '';  //条件により生成する
    $formatYear = '<span style="font-weight:bold;">%s年</span><br />';

//$linkYearを条件により作成し、$_SESSION['printyear']を今処理中の年を入れる。これは1年に1度しか処理させないため
    //今まで出力していた年とは違う場合=初めてその年を出力するとき
    if ($_SESSION['printyear']!=$year) {  //初期値は""空白である。2回目以降呼び出されると最後に処理した年となる
      //※今年の記事しかない場合に2回目に呼ばれると$_SESSION['printyear']が今年から更新されないので引っかからない
      $linkYear = sprintf($formatYear, $year);  //1年目「年+改行」
      $_SESSION['printyear']=$year;           //[年+改行]出力した年を記録
      if($currentYear != $year){        //今年ではない場合
	$linkYear = '<br />'.$linkYear; //さらに頭に[改行]を加える「[改行]+年+[改行]」
      }
    }
    //2回目に呼ばれた時の対策1.:今月だったら間違いなし。不十分。今月書いてなかったらダメ
    else if (($currentMonth == $month) AND ($currentYear == $year)){
      $linkYear = sprintf($formatYear, $year);  //1年目「年+改行」
      $_SESSION['printyear']=$year; //[年+改行]出力した年を記録 
    }
    //そうでない場合は初期値$linkYear = ''

    //'[改行]or[無]2020[改行]' or '無' + '<a href='.$url.' style="white-space: nowrap;">6月</a>'
    return $linkYear.$linkMonth;  //$link_htmlを$linkYear + $linkMonthに加工して返す
}
add_filter('get_archives_link', 'my_archives_link');

Replacing Japanese Slugs with "post-"

Though there isn't a dedicated post for it, this also modifies wordpress/wp-content/themes/function.php. This should be updated alongside the one above.

/*
* スラッグ名が日本語だったら自動的に投稿タイプ+id付与へ変更(スラッグを設定した場合は適用しない)
*/
function auto_post_slug( $slug, $post_ID, $post_status, $post_type ) {
    if ( preg_match( '/(%[0-9a-f]{2})+/', $slug ) ) {
//        $slug = utf8_uri_encode( $post_type ) . '-' . $post_ID; 
        $slug = utf8_uri_encode( $post_type ); 
//        $slug = utf8_uri_encode( 's15bravetune' ); 
    }
    return $slug;
}
add_filter( 'wp_unique_post_slug', 'auto_post_slug', 10, 4  );

Leave a Reply