0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WPでページ保存→サーバー内ファイル参照→特定のページで特定の文字にリンクを適用

Posted at

wp-content/uploads/test-api 以下に参照したいcsvファイルを格納
(以下'/test_api/link/test.csv')

wordpress の function.php の一番下にコードを貼り付け。(前述のcsvのファイルリンクは自環境に応じて編集)

[テストで上手くいったcsvの画像]
image.png
このように、1行目にid, text(←リンクを適用したいテキスト), link(ファイルリンク)を設定。
csvファイルを保存して閉じる→開いて編集し上書き保存したものだと、phpコードが上手く機能しなかったため、ぶっつけ本番でcsvファイルを作成するか、csvファイルは閉じずに開いたままで編集保存→wordpressのcsvを上書き保存 するのが良い。
クイック更新でも反映されていた。

add_filter('wp_insert_post_data', function($data, $postarr) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $data;

    $current_post_id = $postarr['ID'];
    $content = $data['post_content'];

    $upload_dir = wp_upload_dir();
    $csv_path = $upload_dir['basedir'] . '/test_api/link/test.csv';

    if (file_exists($csv_path) && ($handle = fopen($csv_path, "r")) !== FALSE) {
        
        // 1行目(id, target, linkの見出し)を読み飛ばす
        fgetcsv($handle);

        while (($csv_row = fgetcsv($handle)) !== FALSE) {
            if (count($csv_row) < 3) continue;

            // Excel特有のゴミや空白を除去
            $target_id = trim($csv_row[0]);
            $keyword   = trim($csv_row[1], " \t\n\r\0\x0B\xEF\xBB\xBF\"");
            $link_url  = trim($csv_row[2]);

            // 保存中のIDとCSVのIDが一致した場合のみ実行
            if ($current_post_id == $target_id && $keyword && $link_url) {
                
                // すでにそのリンクが貼られていないかチェック
                if (strpos($content, $link_url) === false) {
                    $link_html = '<a href="' . esc_url($link_url) . '">' . esc_html($keyword) . '</a>';
                    // 最初の1回だけ置換
                    $content = preg_replace('/' . preg_quote($keyword, '/') . '/', $link_html, $content, 1);
                }
            }
        }
        fclose($handle);
    }

    $data['post_content'] = $content;
    return $data;
}, 10, 2);
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?