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?

wordpressの全ページをクロールし、ファイルリンクされているテキストを抽出

Posted at

wordpressの全ページをクロールし、ファイルリンクされているテキストを抽出する。
抽出結果はcsvとして出力する。
ページid, テキスト, ファイルリンク
を出力する。
以下は、上記フローを行うためのプログラム

「ツール」の中に 上記のcsvを出力させるメニューを追加する
コードをまとめてfunciton.php で実装するもの。

// 管理画面の「ツール」メニューの中に専用ページを作る
add_action('admin_menu', function() {
    add_management_page(
        'CSVエクスポート', // ページのタイトル
        'CSVエクスポート実行', // メニューの文字
        'manage_options',
        'export-links-csv', // メニューのID(スラッグ)
        'execute_csv_export_logic' // 実行する関数名
    );
});

// ページを開いた時に動くメイン処理
function execute_csv_export_logic() {
    $upload_dir = wp_upload_dir();
    $export_path = $upload_dir['basedir'] . '/test_api/link/exported_links.csv';

    // フォルダがない場合は作成
    if (!file_exists(dirname($export_path))) {
        mkdir(dirname($export_path), 0755, true);
    }

    $posts = get_posts([
        'post_type'   => 'any',
        'post_status' => 'publish',
        'numberposts' => -1,
    ]);

    $handle = fopen($export_path, 'w');
    fwrite($handle, "\xEF\xBB\xBF"); // BOM追加
    fputcsv($handle, ['id', 'target', 'link']);

    $count = 0;
    foreach ($posts as $post) {
        if (preg_match_all('/<a\s+[^>]*href="([^"]+)"[^>]*>(.*?)<\/a>/i', $post->post_content, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $url = $match[1];
                $text = strip_tags($match[2]);
                fputcsv($handle, [$post->ID, $text, $url]);
                $count++;
            }
        }
    }
    fclose($handle);

    echo '<div class="wrap"><h1>CSVエクスポート完了</h1>';
    echo '<p>合計 ' . $count . ' 件のリンクを抽出しました。</p>';
    echo '<p>保存先パス: <code>' . $export_path . '</code></p>';
    echo '<p>FTP等で上記ファイルをダウンロードしてください。</p></div>';
}
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?