サポート » 使い方全般 » コメントが無記名である時の「匿名」という名前の変更

  • 解決済 developer

    (@6flat)


    次のようなコードでコメントが無記名である時の「匿名」という名前の表示を変更していたのですが、こちらのページにある様にWordPress4.4からコメントウィジェットで意図しない表示になってしまうようになりました。

    function rename_anonymous($author) {
      global $comment;
    
      if( empty( $comment->comment_author ) ) {
        if( !empty( $comment->user_id ) ) {
          $user = get_userdata( $comment->user_id );
          $author = $user->user_login;
        } else {
          $author = '無記名';
        }
      } else {
        $author = $comment->comment_author;
      }
    
      return $author;
    }
    add_filter( 'get_comment_author', 'rename_anonymous' );

    リンク先にも解決方法は書いてあるのですが、そもそもなぜコメントウィジェットでこのような表示になってしまうのでしょうか。
    また、この問題に対する適切な対応が他にあればそちらも知りたいです。
    よろしくお願い致します。

4件の返信を表示中 - 1 - 4件目 (全4件中)
  • コメントウィジェットは global 変数の $comment にコメントオブジェクトを入れないからです。代わりに get_comment_author() の第3パラメータを使えばよいのではないでしょうか(検証していません)。

    置き換えだけなら gettext フィルターを使うと簡単です。
    Plugin API/Filter Reference/gettext « WordPress Codex

    トピック投稿者 developer

    (@6flat)

    gblsmさん、ご回答ありがとうございます。

    コメントウィジェットの表示と通常のコメント表示ではコメントを取得する方法が異なるのですね。
    アドバイスして下さった get_comment_author の第3パラメータの指定をする方法と gettext フィルターによる置き換えを試してみようと思いますが、結局表示を置き換えるだけなのであればコスト的にも最初のリンク先にある方法で良いのかもしれないと思えてきました…。

    検証してみました。以下のどちらか一方で。

    add_filter( 'gettext', 'rename_anonymous_type1', 20, 3 );
    function rename_anonymous_type1( $translated_text, $text, $domain ) {
    	switch ( $text ) {
    		case 'Anonymous' :
    			$translated_text = '無記名';
    			break;
    	}
    	return $translated_text;
    }

    または

    add_filter( 'get_comment_author', 'rename_anonymous_type2', 20, 3 );
    function rename_anonymous_type2( $author, $comment_ID, $comment ) {
    	if ( empty( $comment->comment_author ) ) {
    		if ( $comment->user_id && $user = get_userdata( $comment->user_id ) ) {
    			//変更不要	$author = $user->display_name;
    		} else {
    			$author = '無記名';
    		}
    	} else {
    		//変更不要	$author = $comment->comment_author;
    	}
    	return $author;
    }

    トピック投稿者 developer

    (@6flat)

    自分でもほぼ同じ内容で試してみましたが、gettext よりは get_comment_author の方がほんの少しメモリのコストが低い様だったので後者を利用してみようと思います。
    (実行時間の差がどれくらいあるのかは分かりません)

    検証までして下さりありがとうございました。

    ちなみに私のコードは次のようになりました。

    function rename_anonymous( $author = '', $comment_ID = 0, $comment ) {
      if( empty( $comment->comment_author ) && empty( $comment->user_id ) ) {
        $author = '無記名';
      }
    
      return $author;
    }
    add_filter( 'get_comment_author', 'rename_anonymous', 20, 3 );

4件の返信を表示中 - 1 - 4件目 (全4件中)
  • トピック「コメントが無記名である時の「匿名」という名前の変更」には新たに返信することはできません。