Im trying to create a very simple HEART button plugin on WordPress. It is one of my very first plugins. What I am trying to do is when the button in the form is clicked, so the icon that is inside it, will be replaced/changed for another one.
Here is my code:
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;
}
Right now, the emoji that appears when the form is not submitted yet is: ❤ and i would like it to be replaced for: 😜
I tried using the onclick function before, but it doesn’t really work, because the page needs to be updated (it has to send information to the database).
The else if doesn’t really work. It doesn’t happen anything when I click on the heart. It loads the page, but the heart is still there.
Any ideas or suggestions on how I could solve it? Thanks
Advertisement
Answer
For future recording, I solved it like this:
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 { /*when the button is clicked so this happens: 😜*/ return $content . "<form method=POST id="heart-btn-clicked"> <input type=hidden name=heart-btn-clicked value=$id> <button id="heart-btn-clicked">😜</button> </form>"; } } return $content; }