2

A friend created a plugin for me which allows the users to mark posts as read or unread. The code of this plugin is the following :

edit of the code !

<?php
/**
 * @package Read-Unread
 * @version 1.0
 */
/*
Plugin Name: Read-Unread
Plugin URI: http://www.google.fr
Description: Read-Unread plugin
Author: Moi
Version: 1.0
Author URI: http://www.google.fr
*/

global $wpdb;

$table_name = $wpdb->prefix . "users_read"; 

$sql = "CREATE TABLE IF NOT EXISTS `$table_name` (
  `ID_USER` int(11) NOT NULL,
  `ID_POST` int(11) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

dbDelta( $sql );

function all_css()
{
    echo '
    <style>
        .post-read
        {
            cursor: pointer;
        }
    </style>';
}

function all_js()
{
    echo '
    <script>
        jQuery(function($)
        {
            $(".post-read").click(function()
            {
                action = $(this).data("action");

                if($(this).data("action") == "read")
                {
                    $(this).attr("src", "http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/LU.png");
                    $(this).attr("title", "Marquer comme Non lu");
                    $(this).data("action", "unread");
                }
                else
                {
                    $(this).attr("src", "http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/NON_LU.png");
                    $(this).attr("title", "Marquer comme Lu");
                    $(this).data("action", "read");
                }

                postID = $(this).data("id");

                var data = {
                    "action": action,
                    "idPost": postID
                };

                $.post("/wp-admin/admin-ajax.php", data, function(response)
                {

                });
            });
        });
    </script>';
}

function ajax_read() {
    global $wpdb;

    $idUser = intval(get_current_user_id());
    $idPost = intval($_POST['idPost']);

    $table = $wpdb->prefix . "users_read";
    $data = array('ID_USER' => $idUser, 'ID_POST' => $idPost);
    $format = array('%d','%d'); 

    $res = $wpdb->insert( $table, $data, $format );

    if($res == false)
    {
        return 1;
    }

    return 0;

    die();
}

function ajax_unread() {
    global $wpdb;

    $idUser = intval(get_current_user_id());
    $idPost = intval($_POST['idPost']);

    $table = $wpdb->prefix . "users_read";
    $where = array('ID_USER' => $idUser, 'ID_POST' => $idPost);
    $where_format = array('%d','%d'); 

    $res = $wpdb->delete( $table, $where, $where_format );

    if($res == false)
    {
        return 1;
    }

    return 0;

    die();
}

add_action( 'wp_ajax_read', 'ajax_read' );
add_action( 'wp_ajax_unread', 'ajax_unread' );

function get_img_read_unread()
{
    global $wpdb;

    $idUser = intval(get_current_user_id());
    $idPost = intval(get_the_ID());

    $msg = '';

    if($idUser > 0 &&  $idPost > 0)
    {
        $read = $wpdb->get_var( "SELECT COUNT(*) FROM wp_users_read WHERE ID_POST=$idPost AND ID_USER=$idUser");

        if($read == 1)
        {
            echo '<img class="post-read" data-action="unread" data-id="' . $idPost . '" src="http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/LU.png" title="Marquer comme Non lu">';
        }
        else
        {
            echo '<img class="post-read" data-action="read" data-id="' . $idPost . '" src="http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/NON_LU.png" title="Marquer comme Lu">';
        }
    }
}

function add_button($content)
{
    global $wpdb;

    $idUser = intval(get_current_user_id());
    $idPost = intval(get_the_ID());

    $msg = '';

    if($idUser > 0 &&  $idPost > 0)
    {
        $read = $wpdb->get_var( "SELECT COUNT(*) FROM wp_users_read WHERE ID_POST=$idPost AND ID_USER=$idUser");

        if($read == 1)
        {
            $msg = '<img class="post-read" data-action="unread" data-id="' . $idPost . '" src="http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/LU.png" title="Marquer comme Non lu">';
        }
        else
        {
            $msg = '<img class="post-read" data-action="read" data-id="' . $idPost . '" src="http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/NON_LU.png" title="Marquer comme Lu">';
        }
    }
$posttype = get_post_type( get_the_ID() );
if ($posttype == post)
{
    return $content . $msg;
}
else
{
    return $content;
}
}

add_filter('the_content', 'add_button');

add_action( 'wp_footer', 'all_js' );

add_action( 'wp_head', 'all_css' );


?>

I would like to mark as read a post when a post is opened by a user. So how could I do that ?

If i am not understandable enough, please let me know and i'll try to explain better.

Thank you.

Corentin

2
  • Just some notes about the plugin: The AJAX client code won't work if the WP installation is not located at the document root (/wp-admin/) and it ignores WP errors. The MySQL table seems to contain an unused column (READ int(11)) and the AJAX functions allow users to insert an arbitrary amount of data into the database (duplicate rows allowed, no validity check of $_POST['idPost']). Static URLs are (almost) never a good idea, unless you are referencing a different domain. intval(get_current_user_id()) is the same as get_current_user_id() (which always returns ints). Commented Jul 31, 2014 at 9:40
  • Thank you for taking the time to comment. I did a little mistake, I didn't post the actual code, some change have been done. So there is no more (READ int(11)) And the plugin actually works ! Thank you for your comment, i'll make these changes ;) Commented Jul 31, 2014 at 9:46

1 Answer 1

0

I did not test this, but something like this should work. Edit the function all_js in your plugin file and add these lines:

$.post("/wp-admin/admin-ajax.php", {
  idPost: $(".post-read").data("id"),
  action: "read"
}, function(response) {
  // Handle errors etc.
});

You also need to ensure that the button data changes when the AJAX request is made.

Here is an improved script (still far from perfect, but an improvement):

jQuery(function($)
{
    var button = $(".post-read"),
        postId = button.data("id");

    // Updates button attributes to match its data-action attribute
    function updateButton() {
        if(button.data("action") == "unread")
        {
            button.attr("src", "http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/LU.png");
            button.attr("title", "Marquer comme Non lu");
        }
        else
        {
            button.attr("src", "http://corentinbuet.fr/wordpress/wp-content/plugins/Read-Unread/NON_LU.png");
            button.attr("title", "Marquer comme Lu");
        }
    }

    // Mark post as read
    $.post("/wp-admin/admin-ajax.php", {
        idPost: postId,
        action: "read"
    }, function(response) {
        // Handle errors etc.
        button.data('action', 'unread');
        updateButton();
    });

    $(".post-read").click(function()
    {
        // Fix: Declare variable
        var action = button.data("action");

        var data = {
            "action": action,
            "idPost": postId
        };

        $.post("/wp-admin/admin-ajax.php", data, function(response)
        {
            // Check for errors etc
            // Update button
            button.data("action", (action == "read") ? "unread" : "read");
            updateButton();
        });
    });
});
1
  • Tobias, I believe your code will work (haven't tested it though) but the OP also asked to mark the post as read when the page loads, I don't see that addressed. Commented May 17, 2021 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.