【发布时间】:2021-02-21 14:25:45
【问题描述】:
我试图在 Wordpress 上创建一个非常简单的 HEART 按钮插件。这是我的第一个插件之一。我想要做的是当单击表单中的按钮时,其中的图标将被替换/更改为另一个。
这是我的代码:
function create_the_heart_button($content){
global $wpdb;
$table_name = $wpdb->prefix . 'hearts_table';
if( is_singular() && in_the_loop() && is_main_query() ){
$id = get_the_ID();
$user_id = wp_get_current_user();
$wpdb->get_results( "SELECT * FROM $table_name WHERE (owner_id = $user_id->ID AND post_id = $id)" );
if($wpdb->num_rows == 0){
return $content .
// next: create a form and add style input type=submit?
"
<form method=\"POST\" id=\"heart-btn-form\">
<input type=hidden name=heart-btn value=$id>
<button id=\"heart-btn\">❤</button>
</form>";
} else if(isset($_POST['heart-btn'])) {
/*when the button is clicked so this happens: 😜*/
return $content .
"
<form id=\"heart-btn-clicked\">
<input type=hidden name=heart-btn-clicked value=$id>
<button id=\"heart-btn\">😜</button>
</form>";
}
}
return $content;
}
目前,尚未提交表单时出现的表情符号是:❤,我希望将其替换为:????
我之前尝试过使用onclick功能,但它并没有真正起作用,因为页面需要更新(它必须向数据库发送信息)。
else if 并没有真正起作用。当我点击心脏时,它不会发生任何事情。它加载了页面,但心脏仍然存在。
关于如何解决它的任何想法或建议? 谢谢
【问题讨论】:
-
您可以在用户元数据中保存被点击的值。如果用户单击按钮,则表单的 id 和值(例如 boolean true)将保存到数据库中。该按钮将检查用户是否在其元数据中具有值并获取您需要的图标。您当前的代码缺少任何数据保存,因此它通常无法正常工作......如果用户单击按钮,您需要在某个地方存储信息。否则系统无法知道用户是否已经点击。如果只是暂时的,您可以使用 cookie 或浏览器存储。确保将其保存在某个地方。
-
谢谢!我有保存的代码。也许我也应该在帖子中包含它。函数 heart_input() { 全局 $wpdb; $table_name = $wpdb->前缀。 'hearts_table'; if(isset($_POST['heart-btn'])){ $post_id = $_POST['heart-btn']; $user_id = get_current_user_id(); $wpdb->query("插入 $table_name(owner_id, post_id) VALUES ($user_id, $post_id)"); } }
标签: javascript html wordpress forms button