1. Template Name: Gemini AI Wpshare247
<?php
/**
* Template Name: Gemini AI Wpshare247
* Description: Template riêng cho trang custom
*/
get_header();
?>
<main id="primary" class="site-main">
<h1><?php the_title(); ?></h1>
<div class="page-content">
<?php
// Nội dung trang
while ( have_posts() ) :
the_post();
the_content();
// $prompt = "Viết 1 đoạn giới thiệu ngắn về WPSHARE247.COM khoảng 500 từ. Giải thích vì sao cần phải học WordPress từ website này....";
// echo wpshare247_call_gemini( $prompt );
// echo '<br/>-----';
// $prompt = "Tính giúp tôi số 1500 * 568 bằng bao nhiêu?";
// echo wpshare247_call_gemini( $prompt );
endwhile;
?>
</div>
</main>
<?php get_footer(); ?>
2. Code này để vào file functions.php
/**
* Shortcode để test Gemini
* Sử dụng: [wpshare247_gemini prompt="Xin chào Gemini"]
*/
function wpshare247_gemini_shortcode( $atts ) {
$atts = shortcode_atts( [
'prompt' => 'Viết 1 đoạn giới thiệu ngắn về WordPress cho sinh viên CNTT.'
], $atts );
$output = wpshare247_call_gemini( $atts['prompt'] );
return "<div class='wpshare247-gemini-output'>" . esc_html( $output ) . "</div>";
}
add_shortcode( 'wpshare247_gemini', 'wpshare247_gemini_shortcode' );
/**
* Gọi API Gemini 2.0 Flash từ WordPress
*
* @param string $prompt Nội dung muốn gửi cho Gemini
* @return string Trả về text của Gemini (hoặc thông báo lỗi)
*/
function wpshare247_call_gemini( $prompt = "" ) {
// API key của bạn
$api_key = "AIzaSyA_l4HGMfcUK5cbtmNfbpf5eHVDpGWOK3EIqs"; // Đã thay bằng KEY Gemini vừa tạo
// Endpoint Gemini 2.0 Flash
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$api_key";
// Prompt muốn gửi lên Gemini
// Dữ liệu request
$data = [
"contents" => [[
"parts" => [["text" => $prompt]]
]]
];
// Gọi API bằng wp_remote_post
$response = wp_remote_post(
$url,
[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => json_encode($data),
'timeout' => 30,
]
);
// Kiểm tra lỗi
if (is_wp_error($response)) {
return "Lỗi khi gọi API: " . $response->get_error_message();
} else {
$http_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$result = json_decode($body, true);
}
return $result['candidates'][0]['content']['parts'][0]['text'] ?? "Không có dữ liệu trả về. ".$http_code;
}