>本教程演示了构建一个WordPress插件,“投票我”,以在帖子中添加投票功能并显示最佳的内容。
密钥功能:
voteme.php
插件文件处理核心功能,包括通过voteme.js
>。
>创建在您的
目录中。 插件标题应为:
voteme.php
wp-content/plugins/voteme
在
<?php /* Plugin Name: Vote Me Plugin URI: [Your Plugin URI] Description: Adds voting to posts. Author: Abbas Version: 0.1 Author URI: [Your Author URI] */ define('VOTEMESURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) ); define('VOTEMEPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );
。 插件结构应类似于以下方式:js
voteme
voteme.js
加入脚本:
激活WordPress Admin面板中的插件。
function voteme_enqueuescripts() { wp_enqueue_script('voteme', VOTEMESURL.'/js/voteme.js', array('jquery')); wp_localize_script( 'voteme', 'votemeajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action('wp_enqueue_scripts', 'voteme_enqueuescripts');
添加投票链接:
>向帖子添加投票链接:
这添加了投票数,并在每个帖子下面链接。
function voteme_getvotelink() { $votemelink = ""; if( get_option('votemelogincompulsory') != 'yes' || is_user_logged_in() ) { $post_ID = get_the_ID(); $votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0'; $link = $votemecount.' <a onclick="votemeaddvote('.$post_ID.');">Vote</a>'; $votemelink = '<div>' . $link . '</div>'; } else { $register_link = site_url('wp-login.php'); $votemelink = '<div><a href="' . $register_link . '">Vote</a></div>'; } return $votemelink; } function voteme_printvotelink($content) { return $content . voteme_getvotelink(); } add_filter('the_content', 'voteme_printvotelink');
ajax投票:
:
voteme.js
:
function votemeaddvote(postId) { jQuery.ajax({ type: 'POST', url: votemeajax.ajaxurl, data: { action: 'voteme_addvote', postid: postId }, success: function(data, textStatus, XMLHttpRequest) { var linkid = '#voteme-' + postId; jQuery(linkid).html(''); jQuery(linkid).append(data); }, error: function(MLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); }
这将处理AJAX请求以增加投票数。
voteme.php
function voteme_addvote() { $results = ''; global $wpdb; $post_ID = $_POST['postid']; $votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0'; $votemecountNew = $votemecount + 1; update_post_meta($post_ID, '_votemecount', $votemecountNew); $results .= '<div>' . $votemecountNew . '</div>'; die($results); } add_action( 'wp_ajax_nopriv_voteme_addvote', 'voteme_addvote' ); add_action( 'wp_ajax_voteme_addvote', 'voteme_addvote' );
以上是为WordPress创建投票插件的详细内容。更多信息请关注PHP中文网其他相关文章!