реально ли для wordpress написать вот что... Как правильно подойти к этому...? Нажимаешь на кнопку, она тебе выводит текст, а то что на кнопку было произведено нажатие отправляется в бд или куда то в файл где к общему числу +1 добавляется. Вероятно стоит подходить к этому реализацией через javascript. Посоветовали подумать в сторону jquery ajax Идеальный вариант, это что бы был общий файл-таблица на которой будет выведен список по типу: № 143 - 1509 нажатий № 144 - 148 нажатий № 145 - 735 нажатий То есть кнопка будет находится в разных записях и каждая иметь свой уникальный текст, который будет показан после нажатия. Может есть подобные готовые решения? Нашел кое что, что практически идеально подходит под требование, но немного не то... http://wp-kama.ru/id_430/plagin-dlya-podscheta-kolichestva-zagruzok-fayla-kamas-click-counter.html И вот ещё тематическую статью нашел: http://lifeexample.ru/php-primeryi-skriptov/schetchik-skachivaniy-dlya-wordpress.html
offtop: Модераторов прошу изменить название темы на "Счетчик нажатий на кнопку в WordPress" Практически решил задачу установкой плагина Kama’s Click Counter и скриптом: PHP: <script type="text/javascript">// <![CDATA[ function showTooltip() { var myDiv = document.getElementById('tooltip'); var myLink = document.getElementById('link'); if(myDiv.style.display == 'none'){ myDiv.style.display = 'block'; myLink.style.display = 'none'; } else { myDiv.style.display = 'none'; } return false; } // ]]></script> <a class="count" href="javascript:;" onclick="showTooltip()" id="link">Показать </a> <div id="tooltip" style="display: none;">Текст текст текст текст текст</div> Но есть проблема. Класс которой отвечает за запись +1 клик в админку (class="count") делает свое дело. Но при нажатии, помимо того что скрипт показывает нужный текст, страница переходит по ссылке ?kcccount=javascript:;!p=302 выдавая ошибку: p=302 id страницы где установлен код. Интересна реализация через Kama’s Click Counter (очень успешно для задачи подходит этот плагин) Но когда я добавляю класс count то код преобразуется в ссылку (href="http://site.ru?kcccount=javascript:;!p=302) вместо того что бы просто быть href="javascript:;" а так как это становится ссылкой, меня соответственно перебрасывает.
Привожу на обозрение код плагина. В чем суть относительно выяснил. Только лишь если проходишь по ссылке http://site.ru?kcccount=javascript:;!p=302 происходит запись в базу +1 клик. Может как то можно реализовать, что бы посылался запрос, но без редиректа? PHP: <?php /* Plugin Name: ¤ Kama's Click Counter Plugin URI: http://wp-kama.ru/?p=430 Description: Счетчик загрузок файла. Считает количество кликов по ссылке. Используйте в тексте <code>[download=url]</code>. Или добавьте к ссылке class <code>count</code> - <a class="count" href="урл">текст</a> Version: 2.2.6 Author: Kama Author URI: http://wp-kama.ru/ */ define('KCC', 'kama-clic-counter'); // plugin folder name class kcc { var $opt; // options const OPT_NAME = 'kcc_options'; // options name var $table_name = 'kcc_clicks'; // table name without wp prefix var $count_key = 'kcccount'; var $link_data, $redirect_preffix, $not_count; public static function instance(){ static $done = false; if(!$done) $done = new kcc(); return $done; } private function __construct(){ $this->opt = get_option(self::OPT_NAME); $this->table_name = $GLOBALS['table_prefix'] . $this->table_name; $this->redirect_preffix = get_option('siteurl').'?kcccount='; add_filter('the_content', array($this, 'modify_in_content') ); add_filter('the_excerpt', array($this, 'clear_excerpt') ); add_filter('init', array($this, 'redirect'), -10); if( is_admin() ) $this->admin_init(); } /* counting part -------------------------------------- */ // add clicks by given url function do_count($url){ global $wpdb; $val = $this->real_url($url); $link_url = $wpdb->escape($val[0]); $in_post = $val[1] ? $wpdb->escape($val[1]) : 0; $sql = "UPDATE {$this->table_name} SET link_clicks=(link_clicks + 1) WHERE in_post=$in_post AND link_url='$link_url'"; if( $return = $wpdb->query($sql) ) return $return; // Если первый раз считаем $link_clicks = $this->not_count ? 0 : 1; $link_date = current_time('mysql'); //gmdate('Y-m-d H:i:s', (time() + (get_option('gmt_offset') * 3600))); $link_name = preg_replace('@(https?|ftp)://@', '', $link_url); $file_size = ''; if( $this->is_file($link_url) ){ $file_size = $this->file_size($link_url); $link_name = basename($link_url); $link_title = preg_replace('@(.*)\..*$@', '\\1', $link_name); $link_title = preg_replace('@[_-]@', ' ', $link_title); $link_title = ucwords($link_title); } $attach_id = 0; if( $attach = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE post_type='attachment' AND guid='$link_url'") ){ $attach_id = $attach->ID; $link_title = $attach->post_title; $link_description = $wpdb->escape($attach->post_content); $link_date = $attach->post_date; } else { $link_title = $this->gettitle($link_url); } $data = compact( 'attach_id', 'in_post', 'link_clicks', 'link_name', 'link_title', 'link_description', 'link_date', 'link_url', 'file_size' ); $data = stripslashes_deep( $data ); // stripslashes внутри массива $wpdb->insert( $this->table_name, $data ); return (int)$wpdb->insert_id; } // convert relative path ("/blog/dir/file" or "dir/this/file") into absolute (from blog's index.php) and clean url function real_url($url){ $url = urldecode($url); //преобразовываем кирилицу и другие url символы в нормальные //чистим ID поста добавляемый в URL плагином $url_split = explode('!p=', $url); $url = $url_split[0]; $post_id = $url_split[1]; $url = preg_replace ("/#.*$/",'',$url); // delete the #anchor part if( !preg_match("@^(https?|ftp)://@i", $url) ) $url = get_option('siteurl') . ( preg_match("@^/@", $url) ? '' : '/' ) . $url; return array($url, $post_id); } function is_file($url){ $extensions = array ("ace", "arj", "bin", "bz2", "dat", "deb", "gz", "hqx", "pak", "pk3", "rar", "rpm", "sea", "sit", "tar", "wsz", "zip", "aif", "aiff", "au", "mid", "mod", "mp3", "ogg", "ram", "rm", "wav", "ani", "bmp", "dwg", "eps", "eps2", "gif", "ico", "jpeg", "jpg", "png", "psd", "psp", "qt", "svg", "swf", "tga", "tiff", "wmf", "xcf", "avi", "mov", "mpeg", "mpg", "c", "class", "h", "java ", "jar", "js", "bat", "chm", "cur", "dll", "exe", "hlp", "inf", "ocx", "pps", "ppt", "reg", "scr", "xls", "css", "conf", "doc", "ini", "pdf", "rtf", "ttf", "txt"); $ext = preg_replace('@.*\.([a-zA-Z0-9]+)$@', '\\1', $url); if( in_array($ext, $extensions) ) return $ext; return false; } // return title of a (local or remote) webpage function gettitle($url){ $file = @file_get_contents($url); if( preg_match("@<title>(.*)</title>@is", $file, $out) ) return addslashes($out[1]); return ""; } // to get file size function file_size($url){ if(strpos($url, get_option('siteurl'))===false){ $url = str_replace(' ', '%20', $url); if(function_exists('get_headers')) { $headers = @get_headers($url, 1); if($headers['Content-Length']=='') return; $size = $headers['Content-Length']; } else { $file = @file_get_contents($url); if($file == false) return; $size = strlen($file); } } else { $file_dir = preg_replace("@^/(.*)@", '$1', $url); $file_dir = preg_replace("@^https?://[^/]+/(.*)@", '$1', $file_dir); $file = ABSPATH . $file_dir; $size = @filesize($file); } $i = 0; $type = array(" B", " KB", " MB", " GB"); while( ($size/1024)>1 ) { $size=$size/1024; $i++; } return substr($size, 0, strpos($size,'.')+2).$type[$i]; } /* text replacement part -------------------------------------- */ // the one that starts it all function modify_in_content($content){ if( $this->opt['links_class'] ){ $content = preg_replace_callback ("@<a ([^>]*class=['\"]{$this->opt['links_class']}[^>]*)>(.+?)</a>@", array($this, do_simple_link), $content); } $content = preg_replace_callback ("@\[download=([^\]]*)\]@", array($this, do_download), $content); return $content; } // parses string to detect and process pairs of tag="value" function do_simple_link($match){ $link_attrs = $match[1]; $link_anchor = $match[2]; preg_match_all ('@[^=]+=([\'"])[^\\1]+?\\1@', $link_attrs, $args); foreach($args[0] as $pair){ list($tag, $value) = explode("=", $pair, 2); $value = trim( trim( trim($value, "'"), '"' ) ); $args[trim($tag)] = $value; } unset($args[0]); unset($args[1]); $args['href'] = $args['href']. ($this->opt['in_post'] ? '!p=' . $GLOBALS['post']->ID : ''); if( $this->opt['add_hits'] ){ $this->get_link_data($args['href']); // получаем данные ссылки if( $this->link_data->link_clicks ){ if ( $this->opt['add_hits']=='in_title' ){ $args['title'] = "(кликов: {$this->link_data->link_clicks})". $args['title']; } else { $after = ($this->opt['add_hits']=='in_plain') ? ' <span class="hitcounter">(кликов: '. $this->link_data->link_clicks .')</span>' : ''; } } } $args['href'] = $this->redirect_preffix . $args['href']; $link_attrs=''; foreach($args as $key => $value) $link_attrs .= "$key=\"$value\" "; $link_attrs = trim($link_attrs); return "<a {$link_attrs}>{$link_anchor}</a>$after"; } function do_download($match){ $url = $match[1].($this->opt['in_post'] ? '!p=' . $GLOBALS['post']->ID : ''); // первый раз считаем if( !$this->get_link_data($url) ){ $this->not_count = true; $this->do_count($url); $this->get_link_data($url); } $redirect_file = $this->redirect_preffix . $this->link_data->link_url . ($this->opt['in_post'] ? '!p='.$GLOBALS['post']->ID : ''); $tpl = str_replace('[link_url]', $redirect_file, stripslashes($this->opt['download_tpl'])); if( preg_match('@[icon_url]@', $tpl) ){ $_url = $this->link_data->link_url; $extension = preg_replace('@.*\.([a-zA-Z0-9]+)$@', '\\1', $_url); $_icon_path = '/'. KCC ."/icons/"; $icon_link = WP_PLUGIN_URL . (file_exists(WP_PLUGIN_DIR . $_icon_path."$extension.jpg" ) ? ($_icon_path."$extension.jpg") : ($_icon_path.'default.jpg') ); $tpl = str_replace('[icon_url]', $icon_link, $tpl); } preg_match('@\[link_date:([^\]]+)\]@', $tpl, $date); $tpl = str_replace($date[0], mysql2date($date[1], $this->link_data->link_date), $tpl); $tpl = preg_replace_callback('@\[([^\]]+)\]@', array($this, do_download_callback), $tpl ); $edit_link = '<a href="/wp-admin/options-general.php?page='. KCC .'/'. basename(__FILE__) . '&edit_link=' . $this->link_data->link_id . '">[Изменить cсылку]</a>'; return $tpl . (current_user_can('edit_plugins') ? $edit_link : ''); } function do_download_callback($match){ return $this->link_data->$match[1]; } function get_link_data($url){ global $wpdb; $val = $this->real_url($url); $link_url = $wpdb->escape($val[0]); $in_post = $val[1] ? $wpdb->escape($val[1]) : 0; $this->link_data = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$this->table_name} WHERE in_post=%d AND link_url='%s'", $in_post, $link_url) ); return $this->link_data; } function clear_excerpt($text){ return preg_replace("@\[download=([^\]]*)\]@", '', $text); } /* admin part -------------------------------------- */ function admin_init(){ register_activation_hook( __FILE__, array($this, 'activation') ); //register_deactivation_hook( __FILE__, array($this, 'deactivation' ) ); add_action( 'admin_menu', array($this, 'admin_menu') ); add_action('delete_attachment', array($this, 'delete_link_by_attach_id') ); add_action('edit_attachment', array($this, 'update_link_with_attach') ); } function deactivation(){ global $wpdb; $wpdb->query("DROP TABLE {$this->table_name}"); delete_option(self::OPT_NAME); $base = KCC .'/'. basename(__FILE__); $deactivate_url = wp_nonce_url("plugins.php?action=deactivate&plugin=$base", "deactivate-plugin_$base"); echo "<div class='wrap'> <h2>Опции и таблица в Безе Данных были удалены</h2> <p><strong><a href='{$deactivate_url}'>Нажмите сюда</a>, чтобы закончить деинсталяцию. Плагин будет деактивирован автоматически.</strong></p> </div>"; } function activation(){ global $wpdb; if( $wpdb->get_var("SHOW TABLES LIKE '{$this->table_name}'") == $this->table_name ){ // $wpdb->query("ALTER TABLE {$this->table_name} ALTER COLUMN link_clicks SET default '1'"); return true; } $charset_collate = (!empty($wpdb->charset) && !empty($wpdb->collate)) ? "DEFAULT CHARSET=$wpdb->charset COLLATE $wpdb->collate" : "DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; $sql = "CREATE TABLE `{$this->table_name}` ( `link_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `attach_id` int(10) UNSIGNED NOT NULL default '0', `in_post` int(10) UNSIGNED NOT NULL default '0', `link_clicks` int(10) UNSIGNED NOT NULL default '1', `link_name` varchar(255) NOT NULL, `link_title` varchar(255) NOT NULL, `link_description` tinytext NOT NULL, `link_date` datetime NOT NULL default '0000-00-00 00:00:00', `link_url` varchar(255) NOT NULL, `file_size` varchar(255) NOT NULL, `permissions` enum('yes','no') NOT NULL default 'yes', PRIMARY KEY (`link_id`), KEY in_post(`in_post`) ) $charset_collate;"; $wpdb->query($sql); return $this->def_options(); } function def_options(){ $this->opt = $this->def_option_array(); if( !update_option( self::OPT_NAME, $this->opt ) ) add_option( self::OPT_NAME, $this->opt ); return $this->opt = get_option(self::OPT_NAME); } function def_option_array(){ return array( 'download_tpl' => '<style type="text/css"> .kcc_block{border:5px #E3E3E3 solid; border-radius:5px;padding:10px;margin:7px;clear:both;} .kcc_block:before{clear:both;} .kcc_block a {font-size:200%;} .kcc_block img{float:left;margin:0 15px 0 5px;border:0px!important;box-shadow:none!important;} .kcc_block div{color:#666;} .kcc_block small{color:#ccc;} .kcc_block b{display:block;clear:both;} </style> <div class="kcc_block"> <img class="alignleft" src="[icon_url]" alt="" /> <a href="[link_url]" title="[link_name]">[link_title]</a> <div>[link_description]</div> <small>Скачено: [link_clicks], размер: [file_size], дата: [link_date:d.M.Y]</small> <b><!-- clear --></b> </div>' ,'links_class' => 'count' // проверять class в простых ссылках ,'add_hits' => '' // may be: '', 'in_title' or 'in_plain' (for simple links) ,'in_post' => 1 ); } function admin_menu(){ add_options_page('Kama`s Click Counter', '<img src="/wp-admin/images/media-button-other.gif" width="10" height="10" /> Click Counter', 'manage_options', __FILE__, array($this, 'admin_options_page')); } function admin_options_page(){ if( isset($_POST['save_options']) ){ $array = $this->def_option_array(); foreach($array as $k=>$v){ $this->opt[$k] = $_POST[$k]?$_POST[$k]:''; } update_option( self::OPT_NAME, $this->opt ); $alert = 'Настройки сохранены!'; } elseif( isset($_POST['reset']) ){ $this->def_options(); $alert = 'Настройки сброшены на начальные!'; } elseif( isset($_POST['delete']) ){ return $this->deactivation(); } elseif( isset($_POST['update_link']) ){ unset($_POST['update_link']); if( $this->update_link($_POST['link_id'], $_POST) ) $alert = 'Ссылка обновлена!'; } elseif( $_POST['delete_link_id'] ){ if( $this->delete_links($_POST['delete_link_id']) ) $alert = 'Выбранные ссылка(и) <b>удалены</b>!'; else $alert = 'Ничего <b>не удалено</b>!'; } include WP_PLUGIN_DIR .'/'. KCC .'/admin.php'; } function update_link($id, $data){ global $wpdb; $data = stripslashes_deep($data); $query = $wpdb->update( $this->table_name, $data, array( 'link_id' => $id ) ); if( $data['attach_id']>0 ){ // обновление вложения, если оно есть $up_data = array('post_title' => $data['link_title'], 'post_content' => $data['link_description']); $rrr = $wpdb->update( $wpdb->posts, $up_data, array( 'ID' => $data['attach_id'] ) ); } return $query; } ### Удаление ссылок из БД по переданному массиву ID-шек function delete_links($array_ids=array()){ global $wpdb; foreach($array_ids as $k=>$id) // килл пустые элемены if( !trim($id) ) unset( $array_ids[$k] ); if( !$array_ids ) return false; $sql = "DELETE FROM {$this->table_name} WHERE link_id IN (". implode(',', $array_ids) .")"; return $wpdb->query($sql); } ### Удаление ссылки по ID вложения function delete_link_by_attach_id($attach_id){ global $wpdb; if($attach_id=='') return false; $sql = "DELETE FROM {$this->table_name} WHERE attach_id={$attach_id}"; return $wpdb->query($sql); } ### Обновление ссылки, если обновляется вложение function update_link_with_attach($attach_id){ global $wpdb; $attdata = wp_get_single_post( $attach_id ); $new_data = array( 'link_description' => $attdata->post_content ,'link_title' => $attdata->post_title ,'link_date' => $attdata->post_date ); $new_data = stripslashes_deep($new_data); return $wpdb->update( $this->table_name, $new_data, array( 'attach_id' => $attach_id ) ); } /* redirect ------------------------------------------------------------- */ function redirect(){ $url = trim($_GET[$this->count_key]); if( empty($url) ) return; # считаем $this->do_count( $url ); # перенаправляем $_url = explode('!p=', $url); $url = $_url[0]; if ($is_IIS) { header("Refresh:0;url=$url"); } else { if( !headers_sent() ){ header("Location: $url"); header("Status: 303"); } else { print "<script>location.replace(\"$url\");</script>"; } } exit; } } kcc::instance(); От ошибки избавился удалив кусок кода в конце, то есть: PHP: # перенаправляем $_url = explode('!p=', $url); $url = $_url[0]; if ($is_IIS) { header("Refresh:0;url=$url"); } else { if( !headers_sent() ){ header("Location: $url"); header("Status: 303"); } else { print "<script>location.replace(\"$url\");</script>"; } } exit; но это проблему не решает. Ссылка всё равно остается активной и помимо того, что открывает нужный текст, перебрасывает на http://site.ru?kcccount=javascript:;!p=302
Возможно как то можно сделать что бы всё было обычно, но при добавлении class="count" при клике посылался запрос на то, что стоит в href без перехода/обновления страницы? Нашел немного кода который возможно может помочь: hashcode.ru/questions/35915/jquery-отправка-get-запроса-по-клику-на-ссылку
Учитывая что я в отчаянии и не вижу путь истинный, выкладываю файл плагина, который отвечает за все вышеперечисленные действия: Посмотреть в txt: http://yadi.sk/d/-8d57sQpFUWGM php файл: http://yadi.sk/d/lnYojg1iFUb5y Удалив часть кода: PHP: # перенаправляем $_url = explode('!p=', $url); $url = $_url[0]; if ($is_IIS) { header("Refresh:0;url=$url"); } else { if( !headers_sent() ){ header("Location: $url"); header("Status: 303"); } else { print "<script>location.replace(\"$url\");</script>"; } } exit; Избавился от ошибки, но не избавился от редиректа
Нашел немного инфы на эту тему: 1: http://javascript.ru/forum/events/16503-podschet-kolichestva-klikov-myshi-na-obekt-v-jquery.html 2: http://snipcode.ru/catalog.html?snipid=16 и вот: 3: http://wordpress.org/support/topic/a...te-wp-database 4: http://wordpress.org/plugins/ajax-hits-counter/ 5: http://wordpress.stackexchange.com/q...unter-meta-box Мог бы кто то это всё оптимизировать? Вариант 2 подошел бы. Но не работает в mozilla firefox, а так же сработало всего 1 раз в опере и больше не изменялось число.
Всем спасибо за помощь Вопрос закрыт. Решение: Юзаем тему: http://zarabotat-na-sajte.ru/uroki-html/kak-poschitat-kolichestvo-klikov-po-ssilke.html Таким вот образом выводим текст: HTML: <a href="javascript:;" id="link" onclick="setrate(2); showTooltip()"> Показать </a></p> <div id="tooltip" style="display: none;">Тут текст текст текст текст</div>