v23 – Thomas lösningförslag för onsdagens övning

Övning:

Övning onsdag, vecka 23 – Egen plugin | Coder’s Academy

Lösningsförslag

Som zip-fil.

PHP

<?php
/**
 * @package Fav Posts
 * @version 1.0
 */
/*
Plugin Name: Fav Posts
Description: Lets a logged in user mark posts as favorites.
Author: Thomas
Version: 1.0
*/


// Create a DB table when the plugin is activated
function fav_posts_activate(){

  global $wpdb;
  $table_name = $wpdb->prefix . "fav_posts";
  $charset_collate = $wpdb->get_charset_collate();

  $wpdb-> query("CREATE TABLE IF NOT EXISTS $table_name ( 
    userID bigint(20) NOT NULL,
    postID bigint(20) NOT NULL
  ) $charset_collate");

}
register_activation_hook(__FILE__,"fav_posts_activate");


// Delete the DB table when the plugin is uninstalled
function fav_posts_uninstall(){
  global $wpdb;
  $table_name = $wpdb->prefix . "fav_posts";
  $wpdb->query("DROP TABLE IF EXISTS $table_name");
}
register_uninstall_hook(__FILE__,"plugin_example_uninstall");

// Add a bookmark button to posts
function fav_posts_add_btn($content){
  if(!is_user_logged_in()){ return $content; } 
  $post = get_post();
  return '<button style="display:none" data-post-id="'.$post->ID.
    '" class="post-bookmark-btn btn btn-success"></button>'.$content;
}
add_filter("the_content","fav_posts_add_btn");


// Include JS
function fav_posts_enqueue_scripts(){
  wp_register_script(
    "favPosts",
    plugins_url("fav_posts.js",__FILE__),
    array('jquery')
  );
  wp_enqueue_script("favPosts");
}
add_action("wp_enqueue_scripts","fav_posts_enqueue_scripts");

// Transfer AJAX url to js
function fav_posts_ajax_url_to_js(){
   echo '<script>wpAjaxUrl="'.
    admin_url('admin-ajax.php').'"</script>';
}
add_action("wp_head","fav_posts_ajax_url_to_js");

// Respond to AJAX calls
function fav_posts_ajax($action = false){
  global $wpdb;
  $table_name = $wpdb->prefix . "fav_posts";
  $user = wp_get_current_user();
  $action = $action ? 
    $action : str_replace("fav_posts_","",$_POST["action"]);
  $sql = [
    "set" => "INSERT INTO $table_name VALUES(%s,%s)",
    "get" => "SELECT postID FROM  $table_name WHERE userID =  %s",
    "unset" => "DELETE FROM $table_name WHERE userID = %s && postID = %s"
  ];
  $sql = $sql[$action];

  $q = $wpdb->prepare($sql,[$user->ID,$_POST["postid"]]);
  if($action != "get"){
    $wpdb->query($q);
    fav_posts_ajax("get");
    return;
  }
  header("Content-type: application/json");
  echo(json_encode($wpdb->get_results($q)));
  die();
}
add_action("wp_ajax_fav_posts_set","fav_posts_ajax");
add_action("wp_ajax_fav_posts_get","fav_posts_ajax");
add_action("wp_ajax_fav_posts_unset","fav_posts_ajax");

JS

var $ = jQuery;

$(function(){

  // Make an ajaxCall, 
  // then render/set appearance of bookmark buttons
  function ajaxCall(data){
    $.ajax({
      url: wpAjaxUrl,
      dataType: "json",
      method: "POST",
      data: data,
      success: render
    });
  }

  ajaxCall({action:'fav_posts_get'});

  function render(bookmarked){
    bookmarked = bookmarked.map(function(x){
      return x.postID;
    });
    $('.post-bookmark-btn').show().each(function(){
      var btn = $(this), postid = btn.attr('data-post-id');
      if(bookmarked.indexOf(postid) >= 0){
        btn.html('Unbookmark').addClass('btn-danger');
      }
      else {
        btn.html('Bookmark').removeClass('btn-danger');
      }
    });
  }

  // Click a button to bookmark/unbookmark
  $('.post-bookmark-btn').click(function(){
    var btn = $(this), postid = btn.attr('data-post-id');
    ajaxCall({
      postid: postid,
      action: btn.hasClass('btn-danger') ?
        'fav_posts_unset' : 'fav_posts_set'
    });
    btn.blur();
  });

});
0 votes