这个功能是一直想要的,因为我这人比较懒,写长篇大论得慢慢磨,更喜欢碎片化的信息,想到啥就发啥,所以、还是把动态重新放上来了
以前备份也有动态界面的成品,还是太懒了,恢复比较麻烦,这两天趁着工作之余搭配ai重新写了一个,反正也不用管代码是否规整,能用就行🤣
这里提供部署教程,给需要的小伙伴
WordPress动态功能完整部署指南
我将提供完整的代码和详细的部署步骤
📋 完整代码文件
1. 主题的 functions.php 文件(添加以下代码到末尾)
<?php
// ==================== 动态功能代码 - 开始 ====================
// 注册动态自定义文章类型
function create_shuoshuo_post_type() {
$labels = array(
'name' => '动态',
'singular_name' => '动态',
'add_new' => '发表动态',
'add_new_item' => '发表新动态',
'edit_item' => '编辑动态',
'new_item' => '新动态',
'view_item' => '查看动态',
'search_items' => '搜索动态',
'not_found' => '暂无动态',
'not_found_in_trash' => '回收站中没有动态',
'menu_name' => '动态',
'all_items' => '所有动态'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-status',
'supports' => array('title', 'editor', 'author'),
'show_in_rest' => false
);
register_post_type('shuoshuo', $args);
}
add_action('init', 'create_shuoshuo_post_type');
// 添加动态点赞功能
function add_shuoshuo_likes($post_id) {
if (get_post_type($post_id) == 'shuoshuo') {
add_post_meta($post_id, 'shuoshuo_likes', 0, true);
}
}
add_action('publish_shuoshuo', 'add_shuoshuo_likes');
// 处理点赞AJAX请求 - 支持游客点赞版本
function handle_shuoshuo_like() {
// 安全检查
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'shuoshuo_ajax_nonce')) {
wp_send_json_error('安全校验失败');
}
if (!isset($_POST['post_id'])) {
wp_send_json_error('缺少帖子ID');
}
$post_id = intval($_POST['post_id']);
// 生成唯一标识:优先使用用户ID,游客使用IP地址
if (is_user_logged_in()) {
$user_identifier = 'user_' . get_current_user_id();
} else {
$user_identifier = 'guest_' . md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
}
$user_liked_key = 'shuoshuo_liked_' . $user_identifier;
$user_liked = get_post_meta($post_id, $user_liked_key, true);
$likes = get_post_meta($post_id, 'shuoshuo_likes', true);
$likes = $likes ? intval($likes) : 0;
if ($user_liked) {
// 取消点赞
$likes = max(0, $likes - 1);
delete_post_meta($post_id, $user_liked_key);
$action = 'unliked';
} else {
// 点赞
$likes = $likes + 1;
update_post_meta($post_id, $user_liked_key, time()); // 存储时间戳
$action = 'liked';
}
update_post_meta($post_id, 'shuoshuo_likes', $likes);
// 返回点赞数和操作类型
wp_send_json_success(array(
'likes' => $likes,
'action' => $action,
'is_guest' => !is_user_logged_in()
));
}
add_action('wp_ajax_shuoshuo_like', 'handle_shuoshuo_like');
add_action('wp_ajax_nopriv_shuoshuo_like', 'handle_shuoshuo_like');
// 检查用户是否点赞过的函数
function has_user_liked_shuoshuo($post_id) {
if (is_user_logged_in()) {
$user_identifier = 'user_' . get_current_user_id();
} else {
$user_identifier = 'guest_' . md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
}
$user_liked_key = 'shuoshuo_liked_' . $user_identifier;
return get_post_meta($post_id, $user_liked_key, true) ? true : false;
}
// 加载动态页面脚本和样式
function my_shuoshuo_scripts() {
// 仅在"动态模板"页面加载脚本
if (is_page_template('page-shuoshuo.php')) {
// 加载Font Awesome
wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css', array(), '6.4.0');
// 内联样式
wp_add_inline_style('font-awesome', '
.wordpress-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.wp-header {
text-align: center;
margin-bottom: 30px;
padding: 30px 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 10px;
}
.wp-header h1 {
margin: 0 0 10px 0;
font-size: 2.2rem;
}
.shuoshuo-list {
list-style: none;
padding: 0;
margin: 0;
}
.shuoshuo-item {
background: white;
border-radius: 10px;
padding: 25px;
margin-bottom: 20px;
box-shadow: 0 3px 10px rgba(0,0,0,0.08);
border-left: 4px solid #4361ee;
transition: transform 0.3s, box-shadow 0.3s;
}
.shuoshuo-item:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.shuoshuo-content {
margin-bottom: 15px;
line-height: 1.6;
font-size: 1.1rem;
color: #333;
}
.shuoshuo-meta {
display: flex;
justify-content: space-between;
align-items: center;
color: #6c757d;
font-size: 0.9rem;
flex-wrap: wrap;
gap: 10px;
}
.shuoshuo-time {
display: flex;
align-items: center;
gap: 5px;
}
.shuoshuo-actions {
display: flex;
}
.shuoshuo-action {
display: flex;
align-items: center;
gap: 5px;
color: #6c757d;
cursor: pointer;
transition: all 0.3s;
padding: 5px 10px;
border-radius: 5px;
user-select: none;
}
.shuoshuo-action:hover {
background: #f8f9fa;
color: #4361ee;
transform: scale(1.05);
}
.shuoshuo-action.liked {
color: #e74c3c;
}
.shuoshuo-action.liked:hover {
color: #c0392b;
}
.shuoshuo-action.processing {
opacity: 0.6;
pointer-events: none;
}
.shuoshuo-action.pulse {
animation: pulse 0.3s ease-in-out;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.empty-state {
text-align: center;
padding: 50px 20px;
color: #6c757d;
}
.shuoshuo-pagination {
text-align: center;
margin-top: 30px;
}
.guest-notice {
font-size: 0.8rem;
color: #888;
margin-top: 5px;
}
@media (max-width: 768px) {
.wordpress-container { padding: 15px; }
.shuoshuo-item { padding: 20px; }
.shuoshuo-meta { flex-direction: column; align-items: flex-start; }
}
');
// 加载jQuery(确保已加载)
wp_enqueue_script('jquery');
}
}
add_action('wp_enqueue_scripts', 'my_shuoshuo_scripts');
// ==================== 动态功能代码 - 结束 ====================
?>
2. 页面模板文件 page-shuoshuo.php
在主题根目录创建此文件:
<?php
/*
Template Name: 动态模板
*/
get_header();
?>
<div class="wordpress-container">
<header class="wp-header">
<h1><i class="fas fa-comments"></i> 我的动态</h1>
<p>记录生活点滴,分享心情瞬间</p>
<?php if (!is_user_logged_in()): ?>
<p class="guest-notice">游客也可以点赞哦!</p>
<?php endif; ?>
</header>
<ul class="shuoshuo-list" id="shuoshuoList">
<?php
// 查询动态文章
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$shuoshuo_query = new WP_Query(array(
'post_type' => 'shuoshuo',
'posts_per_page' => 10,
'paged' => $paged,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
));
if ($shuoshuo_query->have_posts()) :
while ($shuoshuo_query->have_posts()) : $shuoshuo_query->the_post();
$likes = get_post_meta(get_the_ID(), 'shuoshuo_likes', true);
$likes = $likes ? $likes : 0;
// 使用新函数检查用户是否已点赞
$user_liked = has_user_liked_shuoshuo(get_the_ID());
?>
<li class="shuoshuo-item">
<div class="shuoshuo-content"><?php the_content(); ?></div>
<div class="shuoshuo-meta">
<div class="shuoshuo-time">
<i class="far fa-clock"></i> <?php echo get_the_date('Y-m-d H:i:s'); ?>
</div>
<div class="shuoshuo-actions">
<div class="shuoshuo-action like-action <?php echo $user_liked ? 'liked' : ''; ?>" data-id="<?php the_ID(); ?>">
<i class="<?php echo $user_liked ? 'fas' : 'far'; ?> fa-heart"></i>
<span class="like-count"><?php echo $likes; ?></span>
</div>
</div>
</div>
</li>
<?php
endwhile;
// 分页
if ($shuoshuo_query->max_num_pages > 1) {
echo '<div class="shuoshuo-pagination">';
echo paginate_links(array(
'total' => $shuoshuo_query->max_num_pages,
'current' => $paged,
'prev_text' => '« 上一页',
'next_text' => '下一页 »'
));
echo '</div>';
}
wp_reset_postdata();
else :
echo '<div class="empty-state">';
echo '<i class="fas fa-comment-dots"></i>';
echo '<h3>还没有任何动态</h3>';
echo '<p>请在WordPress后台添加动态内容</p>';
echo '</div>';
endif;
?>
</ul>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
console.log('动态页面JS已加载');
// 使用事件委托处理点赞
$(document).on('click', '.like-action', function(e) {
e.preventDefault();
var $this = $(this);
var postId = $this.data('id');
console.log('点赞点击,帖子ID:', postId);
// 防止重复点击
if ($this.hasClass('processing')) {
console.log('操作进行中,跳过');
return false;
}
// 标记为处理中
$this.addClass('processing');
// 发送点赞请求
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
action: 'shuoshuo_like',
post_id: postId,
nonce: '<?php echo wp_create_nonce('shuoshuo_ajax_nonce'); ?>'
},
success: function(response) {
console.log('点赞响应:', response);
if (response.success) {
// 安全的数据提取
var data = response.data;
var likesValue = (data && typeof data === 'object' && 'likes' in data)
? data.likes
: (typeof data === 'number' ? data : 0);
console.log('最终点赞数:', likesValue);
var likeCount = $this.find('.like-count');
var likeIcon = $this.find('i');
// 更新点赞数
likeCount.text(likesValue);
// 切换点赞状态
if (data && data.action === 'liked') {
$this.addClass('liked');
likeIcon.removeClass('far').addClass('fas');
console.log('点赞成功,新点赞数:', likesValue);
} else if (data && data.action === 'unliked') {
$this.removeClass('liked');
likeIcon.removeClass('fas').addClass('far');
console.log('取消点赞成功,新点赞数:', likesValue);
} else {
// 备用方案:切换当前状态
$this.toggleClass('liked');
likeIcon.toggleClass('far fas');
}
// 添加动画效果
$this.addClass('pulse');
setTimeout(function() {
$this.removeClass('pulse');
}, 300);
// 如果是游客,显示提示信息(可选)
if (data && data.is_guest && data.action === 'liked') {
$this.append('<span class="guest-notice">已点赞</span>');
setTimeout(function() {
$this.find('.guest-notice').fadeOut(300, function() {
$(this).remove();
});
}, 2000);
}
} else {
console.error('点赞失败:', response.data);
alert('操作失败: ' + response.data);
}
},
error: function(xhr, status, error) {
console.error('点赞请求失败:', status, error);
alert('网络错误,请重试');
},
complete: function() {
// 移除处理中状态
$this.removeClass('processing');
}
});
});
});
</script>
<?php
get_footer();
?>
🚀 部署步骤
步骤1:备份您的网站
在开始之前,请务必备份您的WordPress网站,包括文件和数据库。
步骤2:修改主题文件
- 登录到您的WordPress后台
- 进入 外观 > 主题编辑器
- 找到并打开
functions.php
文件 - 将上面的 第一部分代码 添加到文件末尾
- 保存文件
步骤3:创建页面模板
- 通过FTP或文件管理器访问您的WordPress安装目录
- 导航到
/wp-content/themes/您的主题名称/
- 创建新文件
page-shuoshuo.php
- 将上面的 第二部分代码 复制到文件中
- 保存文件
步骤4:创建动态页面
- 在WordPress后台,进入 页面 > 新建页面
- 设置页面标题为”动态”(或其他您喜欢的名称)
- 在右侧”页面属性”中,选择”动态模板”作为模板
- 发布页面
步骤5:测试功能
- 访问您刚创建的动态页面
- 检查页面是否正常加载,样式是否正确
- 尝试点赞功能(先以游客身份测试,再登录测试)
步骤6:添加动态内容
- 在WordPress后台,您会看到左侧菜单中新增了”动态”选项
- 点击 动态 > 发表动态
- 添加您的第一条动态内容并发布
🔧 故障排除
如果遇到问题,请检查以下几点:
- 白屏或错误:检查PHP代码语法是否正确,特别是分号和括号
- 样式不正常:检查浏览器控制台是否有CSS加载错误
- 点赞功能不工作:检查浏览器控制台的网络选项卡,查看AJAX请求是否成功
- 页面模板不显示:确保页面已正确设置为使用”动态模板”
手机端这个页面很窄,看看
目前全站都还没有做手机端的网页大小适配,快开始了
页面的名字是白色。。。
👌