LoginSignup
1
0

More than 1 year has passed since last update.

会員向けのメール配信機能のショートコードを定義する。

Last updated at Posted at 2022-10-01

カスタム投稿、「メール配信」が合ったとして、その投稿を会員向けにメール配信する場合、真っ先に思いつくのはadd_shortcodeによってそれぞれのユーザー情報を表示してメールを送信しようかと考えましたが、複数宛に送信したいので使えません。
なので投稿本文をstr_replaceで置換して上げて、returnで返すようにしてあげれば簡単に実装できます。
後はwp_mail等で送信します。

functions.php
function mail_shortcodes($user_id,$body){
	$user_data = get_userdata($user_id);
    $shortcodes = array(
        'nickname' => get_user_meta($user_id,'nickname',true),
		'user_email' => $user_data->user_email,
    );

    $shortcd = array();
    $replace = array();
    foreach ($shortcodes as $key => $val) {
        $shortcd[] = '[' . $key . ']';
        $replace[] = $val;
    }
    return str_replace($shortcd,$replace,$body);
}
test.php
$test_body = "[nickname]さん宛にメールします。\n";
$test_body .= "登録メールアドレス[user_email]";
$users = get_users();
foreach($users as $user){
	echo nl2br(mail_shortcodes($user->ID,$test_body));
}

問題点としてWordPressのショートコードとかぶる可能性があるので、[〇〇]ではなく別のもので囲ったほうが良いかもしれません。
{{〇〇}}など

メモ

今回はfunctions.phpに定義しましたが、他でも使える部分なのでプラグイン化したほうが良いと思います。
テーマにロジックを書いてしまうとリニューアルや追加機能を実装する際に、どこまでがその範囲か分からず後悔するため
(以前WordPressでシステムっぽい事をしようとした際にそれで失敗しました。)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0