将 NeoDB 书影音记录整合到 WordPress 中

朋友们,已将该功能整合成一个WordPress插件,可直接看这篇 WordPress 插件-NeoDB Integration 书影音展示页面,更简单易用。

这两篇文章合在一起,是我第一次使用 ChatGPT 协助制作 WordPress 插件的心路历程。

NeoDB 是一个开源免费的书影音收藏社区平台,详情见:NeoDB | 书影音标记 – 豆瓣、GoodReads 和 Google Book 的替代品

本文参考 hcplantern 的 将 NeoDB 记录整合到 Hugo 中 ,实现了将 NeoDB 观影记录添加到 WordPress 页面中,展示页面:NeoDB 书影音

获取 NeoDB Bearer Token

NeoDB API Developer Console 中点击Test Access Token,并 Generate 一个 NeoDB Bearer Token,示例:Th2121_qs-8agMAlSrkE_tzBbcvjsdkjtlCtr9QHX321312312Ytzo8_YmOxjxg

在终端(Terminal)或命令提示符(Command Prompt)中输入以下代码,将 YOUR_TOKEN 替换为 NeoDB Bearer Token。

curl -H "Authorization: Bearer YOUR_TOKEN" https://neodb.social/api/me

设置 Cloudflare worker

注册 Cloudflare worker,点击 Create,创建一个 worker。

最初会展示一个 Hello World 基础案例,点击 Continue to project – Settings – Variables and Secrets。

添加一个环境变量(Environment Variables):

  • Type:text
  • Variable name:NEODB_TOKEN
  • Value:NeoDB Bearer Token,示例:H13121_qs-8agMAlSrkE_tzBbcvjsdkjtlCtr9QHX321312312Ytzo8_YmOxjxg

点击右上角的 Edit code,删除 worker.js 中全部代码,并将 hcplantern 提供的代码(如下)复制黏贴进去。

const myBearer = NEODB_TOKEN; // Assuming 'NEODB_TOKEN' is set in your Cloudflare Worker's environment variables

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
try {
console.log(myBearer)
const url = new URL(request.url);
const category = url.pathname.substring(1);

// Optionally, handle query parameters (e.g., page number)
const page = url.searchParams.get('page') || '1';
// Available values : wishlist, progress, complete
const type = url.searchParams.get('type') || 'complete';

let dbApiUrl = `https://neodb.social/api/me/shelf/${type}?category=${category}&page=${page}`;
const response = await fetch(dbApiUrl, {
method: 'get',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${myBearer}`
}
});

// Check if the response from the API is OK (status code 200-299)
if (!response.ok) {
throw new Error(`API returned status ${response.status}`);
}

// Optionally, modify or just forward the API's response
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
status: response.status
});

} catch (error) {
// Handle any errors that occurred during the fetch
return new Response(error.message, { status: 500 });
}
}const myBearer = NEODB_TOKEN; // Assuming 'NEODB_TOKEN' is set in your Cloudflare Worker's environment variables

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
try {
console.log(myBearer)
const url = new URL(request.url);
const category = url.pathname.substring(1);

// Optionally, handle query parameters (e.g., page number)
const page = url.searchParams.get('page') || '1';
// Available values : wishlist, progress, complete
const type = url.searchParams.get('type') || 'complete';

let dbApiUrl = `https://neodb.social/api/me/shelf/${type}?category=${category}&page=${page}`;
const response = await fetch(dbApiUrl, {
method: 'get',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${myBearer}`
}
});

// Check if the response from the API is OK (status code 200-299)
if (!response.ok) {
throw new Error(`API returned status ${response.status}`);
}

// Optionally, modify or just forward the API's response
const data = await response.json();
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
status: response.status
});

} catch (error) {
// Handle any errors that occurred during the fetch
return new Response(error.message, { status: 500 });
}
}

然后点击 Deploy 部署即可。

注意在这一步中,需要复制保留左侧 Preview 下方的网址,示例 https://xyz-hall-ohxu.user.workers.dev/

WordPress Shortcode

在 WordPress 管理后台,导航到“外观” -> “主题编辑器”。

找到并编辑当前主题的 functions.php 文件。

将以下代码添加到 functions.php 文件中。这段代码创建了一个名为 neodb 的短代码。

注意:将代码中的 https://your-worker-url/ 替换为 Cloudflare worker 中的 https://xyz-hall-ohxu.user.workers.dev/

function neodb_shortcode($atts) {
$atts = shortcode_atts(
array(
'category' => 'book',
'type' => 'complete',
),
$atts,
'neodb'
);

$category = $atts['category'];
$type = $atts['type'];

$url = sprintf('https://your-worker-url/%s?type=%s', $category, $type);

$response = wp_remote_get($url);
if (is_wp_error($response)) {
return '数据获取失败';
}

$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (empty($data['data'])) {
return '没有找到相关数据';
}

ob_start();
?>
<div class="item-gallery">
<?php foreach (array_slice($data['data'], 0, 10) as $value): ?>
<?php $item = $value['item']; ?>
<div class="item-card">
<a class="item-card-upper" href="<?php echo esc_url($item['id']); ?>" target="_blank" rel="noreferrer">
<img class="item-cover" src="<?php echo esc_url($item['cover_image_url']); ?>" alt="<?php echo esc_attr($item['display_title']); ?>">
</a>
<div class="rate">
<?php if (!empty($item['rating'])): ?>
<span><b><?php echo esc_html($item['rating']); ?></b>🌟</span>
<br>
<span class="rating-count"><?php echo esc_html($item['rating_count']); ?>人评分</span>
<?php else: ?>
<span>暂无🌟</span>
<br>
<span class="rating-count"><?php echo esc_html($item['rating_count']); ?>人评分</span>
<?php endif; ?>
</div>
<h3 class="item-title"><?php echo esc_html($item['display_title']); ?></h3>
</div>
<?php endforeach; ?>
</div>
<style>
.item-gallery {
display: flex;
padding: 0 1rem;
overflow-x: scroll;
align-items: baseline;
}
.item-card {
display: flex;
flex-direction: column;
flex: 0 0 17%;
margin: 0 0.5rem 1rem;
border-radius: 5px;
transition: transform 0.2s;
width: 8rem;
}
.item-card:hover {
transform: translateY(-5px);
}
.rate {
text-align: center;
}
.rating-count {
font-size: 0.8rem;
color: grey;
}
.item-cover {
width: 100%;
min-height: 3rem;
border: 2px solid transparent;
}
.item-title {
font-size: 1rem;
text-align: center;
margin: 0;
}
</style>
<?php
return ob_get_clean();
}
add_shortcode('neodb', 'neodb_shortcode');

使用代码

在 WordPress 页面或文章中,使用以下短代码来显示数据:

CleanShot 2024-12-20 at 00.09.10@2x.png

book 可以替换为 movie, tv, podcast, music, game, performance,展示更多数据。

type 可选 wishlist 和 complete,展示想看和看过的内容。

效果示例:https://anotherdayu.com/neodb/

CleanShot 2024-12-19 at 23.56.56@2x.png

另,附上我的 NeoDB主页:https://neodb.social/users/anotherdayu/,和 mastodon 账号:https://mastodon.social/@anotherdayu

4 评论

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注

  1. 用 Cloudflare worker 的意义是啥,看了下代码也就请求了一下接口,怎么不直接在 wp 中调用