概要
woocommerce_downloadable_file_exists
関数は、WooCommerceでダウンロード可能な商品のファイルの存在を確認するために使用されます。この関数は、特にデジタル商品を販売する際によく利用され、以下のような機能の実装で役立ちます。
- ダウンロード商品が購入者に適切に提供されることの確認
- カスタマーサポート対応時にファイルの状態を確認
- 不正なダウンロードを防ぐためのセキュリティチェック
- 商品の更新時に新しいファイルの存在を確認
- 自動メール通知でダウンロードリンクの有効性確認
- ユーザー・アカウント内の注文履歴に基づいてファイルの存在を検証
構文
woocommerce_downloadable_file_exists( $product_id, $download );
パラメータ
$product_id
(int): 商品のID$download
(string): ダウンロードファイルの情報
戻り値
- (bool): ファイルが存在する場合はtrue、存在しない場合はfalseを返します。
プラグインおよびワードプレスのバージョン
- WooCommerce バージョン: 3.0.0以上
- WordPress バージョン: 4.0以上
サンプルコード
サンプルコード1: ダウンロードファイルの存在チェック
$product_id = 123; // 商品のID
$download_file = 'example-file.zip'; // ダウンロードファイル名
if ( woocommerce_downloadable_file_exists( $product_id, $download_file ) ) {
echo 'このファイルは存在します。';
} else {
echo 'ファイルは存在しません。';
}
このサンプルは、特定の商品に関連付けられたダウンロードファイルが存在するかを確認し、結果を表示します。
サンプルコード2: ファイル存在確認によるエラーメッセージの表示
function check_download_file( $product_id, $download_file ) {
if ( ! woocommerce_downloadable_file_exists( $product_id, $download_file ) ) {
// ファイルが存在しない場合、エラーメッセージを表示
add_action( 'woocommerce_thankyou', function() {
echo '<p>ダウンロードファイルが存在しません。</p>';
});
}
}
このサンプルは、支払い完了後にダウンロードファイルが存在しない場合にエラーメッセージを表示します。
サンプルコード3: ショートコードでダウンロードファイルの存在確認
function downloadable_file_exists_shortcode( $atts ) {
$atts = shortcode_atts( array( 'id' => '', 'file' => '' ), $atts );
if ( woocommerce_downloadable_file_exists( $atts['id'], $atts['file'] ) ) {
return 'ファイルは存在しています。';
} else {
return 'ファイルは存在しません。';
}
}
add_shortcode( 'file_exists', 'downloadable_file_exists_shortcode' );
このサンプルでは、ショートコードを使って、ファイルの存在チェックを行い、その結果を表示します。
サンプルコード4: 管理画面でファイルの存在チェック
function admin_check_download_file( $post_id ) {
if ( 'product' === get_post_type( $post_id ) ) {
$download_file = 'example-file.zip'; // 例のファイル
if ( woocommerce_downloadable_file_exists( $post_id, $download_file ) ) {
echo 'この商品にはダウンロード可能なファイルが存在します。';
}
}
}
add_action( 'edit_post', 'admin_check_download_file' );
このサンプルは、商品を編集する際に、その商品のダウンロードファイルが存在するかどうかを確認し、結果を表示します。
サンプルコード5: AJAXリクエストでのファイル存在確認
add_action( 'wp_ajax_check_download_file', 'ajax_check_download_file' );
function ajax_check_download_file() {
$product_id = intval( $_POST['product_id'] );
$download_file = sanitize_text_field( $_POST['file'] );
if ( woocommerce_downloadable_file_exists( $product_id, $download_file ) ) {
wp_send_json_success( 'ファイルは存在します。' );
} else {
wp_send_json_error( 'ファイルは存在しません。' );
}
}
このサンプルは、AJAXリクエストを通じてダウンロードファイルの存在を確認し、結果をJSON形式で返します。
この関数のアクションでの使用可能性
アクション名 | 使用可能 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |