我只是想创建插件,当访问者(用户,访问者,...)访问某些帖子,记住帖子,并增加该帖子的计数器时,我写了这段代码,但有时候,计数器会增加,甚至帖子都没有被查看,或者帖子与其他ID被添加到一个表。可以有人帮我这个,拜托。我知道有插件,我正在尝试做,但仍然想写这个插件
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');
抱歉我的英文不好,提前tnx。
答案 0 :(得分:1)
以下是使用postmeta
表格的方法。
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' );
此外,最好先把它挂钩。这样,每个页面加载只会增加一次计数(the_content
每页可以多次触发,即使在单个页面上也是如此。template_redirect
每个请求只会触发一次)。此外,如果您将数据存储在template_redirect
,则可以使用模板中更新的视图计数,从而为访问者提供更准确的查看次数。
您无需担心数据库表,自定义SQL或其中任何一种。