2010-06-18 55 views
1

我只是想創建一個插件,當訪問者(用戶,訪客,...)訪問某個帖子,記住什麼帖子,並增加該帖子的計數器時,我寫了這個代碼,但有時,計數器遞增,甚至帖子沒有被查看,或者與其他ID一起被添加到表格中。有人可以幫我解決這個問題,我知道這是我想要做的插件,但仍然想寫這個插件。WordPress的創建插件大多數查看帖子的問題?

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

我認爲使用自定義表格有點矯枉過正 - 'postmeta'表格應該給你充足的呼吸空間。你有沒有檢查出現有的插件可能會做你想要實現的? http://wordpress.org/extend/plugins/search.php?q=popular – TheDeadMedic 2010-06-18 11:33:19

+0

我想寫我自己的插件,我不知道postmeta表(meta_id,post_id,meta_key,meta_value)如何可以幫助我,你能我更具體一點? 你也許是我的代碼出了什麼問題? – user147 2010-06-18 12:01:43

回答

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或其他任何問題。

+0

對不起,我遲到的迴應,我會嘗試你的代碼,tnx的答案。 – user147 2010-06-19 10:37:24

+0

對不起,我沒有時間,現在明白它如何與postmeta表,非常感謝你,但仍然,計數器是增加了一些帖子不被查看。例如,ID爲43的職位是增量,並與ID後56是增量,但僅查看ID 43的帖子,可能是什麼問題? – user147 2010-06-22 11:37:40

+0

它看起來像是,當頁面重新加載時,它也會增加,並計數以前的帖子,而不僅僅是當前的帖子。 – user147 2010-06-22 12:51:00