wp_ajax_get_attachment

函式
wp_ajax_get_attachment ( No parameters )

wp_ajax_get_attachment。這個WordPress函式是用來通過AJAX獲取附件資料的。它處理獲取附件資料的伺服器端處理,包括檢查正確的使用者認證和許可權,查詢資料庫中請求的附件資料,並將資料作為JSON編碼的響應返回給客戶端的JavaScript。

獲取附件的Ajax處理程式。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function wp_ajax_get_attachment() {
if ( ! isset( $_REQUEST['id'] ) ) {
wp_send_json_error();
}
$id = absint( $_REQUEST['id'] );
if ( ! $id ) {
wp_send_json_error();
}
$post = get_post( $id );
if ( ! $post ) {
wp_send_json_error();
}
if ( 'attachment' !== $post->post_type ) {
wp_send_json_error();
}
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error();
}
$attachment = wp_prepare_attachment_for_js( $id );
if ( ! $attachment ) {
wp_send_json_error();
}
wp_send_json_success( $attachment );
}
function wp_ajax_get_attachment() { if ( ! isset( $_REQUEST['id'] ) ) { wp_send_json_error(); } $id = absint( $_REQUEST['id'] ); if ( ! $id ) { wp_send_json_error(); } $post = get_post( $id ); if ( ! $post ) { wp_send_json_error(); } if ( 'attachment' !== $post->post_type ) { wp_send_json_error(); } if ( ! current_user_can( 'upload_files' ) ) { wp_send_json_error(); } $attachment = wp_prepare_attachment_for_js( $id ); if ( ! $attachment ) { wp_send_json_error(); } wp_send_json_success( $attachment ); }
function wp_ajax_get_attachment() {
	if ( ! isset( $_REQUEST['id'] ) ) {
		wp_send_json_error();
	}

	$id = absint( $_REQUEST['id'] );
	if ( ! $id ) {
		wp_send_json_error();
	}

	$post = get_post( $id );
	if ( ! $post ) {
		wp_send_json_error();
	}

	if ( 'attachment' !== $post->post_type ) {
		wp_send_json_error();
	}

	if ( ! current_user_can( 'upload_files' ) ) {
		wp_send_json_error();
	}

	$attachment = wp_prepare_attachment_for_js( $id );
	if ( ! $attachment ) {
		wp_send_json_error();
	}

	wp_send_json_success( $attachment );
}

常見問題

FAQs
檢視更多 >