Wordpress creating plugin for most viewed posts problem?

此生再无相见时 提交于 2019-12-11 10:36:03

问题


I just want to create plugin that will when visitor(user,visitor,...) visit some post,remember what post,and to increment counter of that post,I wrote this code,but sometimes,counter is incremented,even post isn't viewed,or post with other Id is added to a table.Can someone help me with this,please.I know that there are plugins for this that I'm trying to do,but still want to write this plugin.

function IncrementPostCount($the_content) {
    global $post;
    global $wpdb;

    if(($post->post_status == 'publish') && (int)$post->ID) {

        if(is_single()) { // just for single post - not for page
            $postID = (int)$post->ID;

            $postTitle = urlencode($post->post_title);
            $postLink = urlencode(get_permalink($post->ID));

            $oneRow = $wpdb->get_row("SELECT * FROM wp_postovi WHERE postAjDi='$postID'");

            if(empty ($oneRow)) {
                $postCounter = 1;
                $data_array = array(
                   'readnTimes' => $postCounter, 
                   'linkPost'=>$postLink, 
                   'TitlePost'=>$postTitle,
                   'postAjDi'=>$postID);
                $wpdb->insert('wp_najcitaniji_postovi', $data_array);                
            }
            else {
                $postCounter = intval($oneRow->readnTimes) + 1;
                $data_array = array('readnTimes' => $postCounter);
                $where_array = array('postAjDi'=>intval($oneRow->postAjDi));
                $wpdb->update('wp_postovi',$data_array,$where_array);
            }

            return $the_content;
        }
        return $the_content;
    }
}
add_filter('the_content','IncrementPostCount');

Sorry on my bad english,tnx in advance.


回答1:


Here's how to do that with the postmeta table.

function IncrementPostCount(){
  if(is_single()){
    global $wp_query;
    $count = get_post_meta( $wp_query->post->ID, 'readnTimes', true );
    $count = empty($count) ? 1 : $count + 1;
    add_post_meta($wp_query->post->ID, 'readnTimes', $count, true) or update_post_meta($wp_query->post->ID, 'readnTimes', $count);
  }
}
add_action( 'template_redirect', 'IncrementPostCount' );

Also, it's better to hook it in earlier. That way, the count is only incremented once per page load (the_content can be fired multiple times per page, even on a single page. template_redirect only fires once per request). Also, if you store the data at template_redirect, you can use the updated view count in the template, giving your visitors an even more accurate view count.

And you don't need to worry about database tables, custom SQL, or any of that.



来源:https://stackoverflow.com/questions/3067394/wordpress-creating-plugin-for-most-viewed-posts-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!