43.全ての記事の一覧をCSV出力するFunctionCode

作成日: 2022/08/24 更新日: 2023/03/25 サイトの紹介と使い方

初めに

  1. 筆者が独自にfunctionを分類、構成しています。
  2. ファイル(置き場所):テーマCocoon childのfunctions.php
  3. 分類コード:22xx

必要な環境

  1. 筆者の環境を提示しますので、それと相応の環境が必要になります。
    1. さくらインターネットのVPS
    2. 権限を持つフォルダ

内容

説明

  1. 機能:全ての記事の一覧をCSV出力します。
  2. 引数:ファイル名
  3. 戻り値:無し
  4. CSVの出力内容
    1. 記事のid
    2. あれば、記事の親カテゴリ
    3. あれば、記事の子カテゴリ
    4. 記事のtag
    5. 記事のタイトル

ソースコード

//<--- 2213
function my_article_list_csv_parts($atts){
  $fh = fopen($atts[0], "w");
  if( $fh ):
	$ret .= "<p>" . $atts[0] . "</p>";
	$rec = "id,parent,child,tag,title,#char,#cat\n";
	fwrite( $fh,$rec );
    $args = array(
	  'posts_per_page'   => 500,
	  'post_type'		 => 'post'
    ); 
    $my_posts = get_posts( $args );
	
	foreach ($my_posts as $p){
	  $rec = strval( $p->ID );
	  $rec .= ",";
	  $cats = get_the_category( $p->ID );
	  if( count($cats) ){
		if( has_tag("21parent",$p) ):
		  $rec .= $cats[0]->name;
		  $rec .= ",,";
		  $rec .= "21parent,";
		elseif( has_tag("22child",$p) ):
		  $par  = get_category( $cats[0]->parent );
		  $rec .= $par->name;
		  $rec .= ",";
		  $rec .= $cats[0]->name;
		  $rec .= ",";
		  $rec .= "22child,";
		elseif( has_tag("81parent_cat",$p) ):
		  $rec .= $cats[0]->name;
		  $rec .= ",,";
		  $rec .= "81parent_cat,";
		elseif( has_tag("82child_cat",$p) ):
		  $par  = get_category( $cats[0]->parent );
		  $rec .= $par->name;
		  $rec .= ",";
		  $rec .= $cats[0]->name;
		  $rec .= ",";
		  $rec .= "82child_cat,";
		else:
	      $rec .= "no tag for article,,";
		endif;
	  }else{
		$rec   .= "none category,,";
	  }
	  $rec .= $p->post_title;
	  $rec .= ",";
	  $ss   = str_replace( array("\r\n", "\r", "\n"), '', $p->post_content );
      $cnt  = mb_strlen( strip_tags($ss), "UTF-8" );
	  $rec .= strval( $cnt );
	  $rec .= ",";
	  $rec .= strval( count($cats) );
	  $rec .= "\n";
	  fwrite( $fh,$rec );
	}
	
	$args = array(
	  'posts_per_page'   => 500,
	  'post_type'		 => 'page'
    ); 
    $my_pages = get_posts( $args );
	
	foreach ($my_pages as $p){
	  $rec = strval($p->ID);
	  $rec .= ",page,,,";
	  $rec .= $p->post_title;
	  $rec .= ",";
	  $ss   = str_replace( array("\r\n", "\r", "\n"), '', $p->post_content );
      $cnt  = mb_strlen( strip_tags($ss), "UTF-8" );
	  $rec .= strval( $cnt );
	  $rec .= ",";
	  $rec .= strval( count($cats) );
	  $rec .= "\n";
	  fwrite( $fh,$rec );
	}
	
	fclose( $fh );
  else:
	$ret .= "file open error";
  endif;
	
  return $ret;
}
// 2213 --->

お問合せ・御要望

お問合せ
Verified by MonsterInsights
タイトルとURLをコピーしました