如何将JQuery/AJAX放入短码?

时间:2012-06-07 作者:ChrisBuck

这个插件的目的是创建一个列表,用户可以通过向上或向下的投票进行修改。短代码应该显示页面上的列表,并在更新数据库时使用JQuery进行fadeIn和fadeOut。

有关该概念的演示,请访问http://bucketlingerwedding.com/80s-music-reception/ (注意:工作代码尚未使用AJAX)。

我想把这个插件放在Wordpress存储库中,但AJAX让我很头疼。以下是最新代码。它只显示一个包含空白内容区域的页面。我需要获得这段代码以使用AJAX更新数据库,并避免重新加载页面,以便我可以在动画/转换中工作。

对代码进行了注释,以反映我对正在尝试执行的操作的理解。

Code:

/*
*
*
SHORTCODE
*
*
*/

add_shortcode(\'list-up-down\', \'cb_lud_scfunc\');

//This creates the shortcode.
function cb_lud_scfunc() {
//Define some basic variables.
global $wpdb;
$cb_lud_prefix = $wpdb->prefix;
$cb_lud_table = $cb_lud_prefix . \'cb_list_up_down\';
$cb_lud_homeurl = home_url();
$cb_lud_upimg = plugins_url(\'list-up-down/images/up-arrow.png\', _FILE_);
$cb_lud_downimg = plugins_url(\'list-up-down/images/down-arrow.png\', _FILE_);
$cb_lud_sample_query = $wpdb->query(\'SELECT * FROM \'.$cb_lud_table);
$cb_lud_field1_name = $wpdb->get_col_info(\'name\',1);
$cb_lud_field2_name = $wpdb->get_col_info(\'name\',2);

/*
CREATE THE JAVASCRIPT/JQUERY FUNCTION
*/
//Create the Javascript and AJAX
//add_action(\'init\', \'cb_lud_action_javascript\');

function cb_lud_action_javascript() {
?>
<script type=\'text/javascript\' src=\'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\'></script>
 <script type=\'text/javascript\' >

$(document).ready(function(){
//JQuery for the submission of a new list item.
    $(\'input\').click(function(e){
        e.preventDefault(); //put e in function.
        var ajaxurl = \'<?php echo admin_url(\'admin-ajax.php\'); ?>\';

        if ($(this).hasClass(\'up-arrow\')) {
            var arrowdirection = \'up\';
            var entry = $(this).val();
        }
        else if ($(this).hasClass(\'down-arrow\')) {
            var arrowdirection = \'down\';
            var entry = $(this).val();
        }

        var data = {
            action: \'cb_lud_arrow_action\',
            arrow: arrowdirection,
            entryID: entry
        };

        $.ajax ({
            type: \'POST\',
            url: ajaxurl,
            data: data,
            success: function(){
                $(\'.line-items-rows\').fadeOut(\'fast\').delay(1000).fadeIn(\'fast\');
            }
        });

        /*var data = {
            action: \'cb_lud_up_arrow_action\',
            arrow-direction: \'up\',
            entry-id: arrow-entry-id
        };

    $.ajax ({
        type: \'POST\',
        url: ajaxurl,
        data: data,
        success: function(){

//$(\'#cb_lud_list\').fadeOut(\'fast\').delay(1000).$(\'#cb_lud_list\').fadeIn(\'fast\');
            $alert(\'it worked\');
        }
    });*/
});
});

</script>
<?php
//End Javascript function.  
}

//Call the javascript function.
//Rather than hook into an action, call whenever shortcode is in a page.
cb_lud_action_javascript();

/*
*
CREATE THE AJAX (HELP!)
*
*/

/*
ARROW CALLBACK
*/

//Use the Wordpress AJAX functions
//Apparently, there has to be an if->then statement depending on whether the user is an admin.
if( is_admin() )
{
add_action(\'wp_ajax_cb_lud_arrow_action\', \'cb_lud_arrow_callback\');
add_action(\'wp_ajax_nopriv_cb_lud_arrow_action\', \'cb_lud_arrow_callback\');
}
else
{
//Assume the \'else\' is the normal execution of the shortcode.
     //Want to get the POST values from the form, above.
     //These don\'t seem to be working.

    $cb_lud_entry_id = $_POST[\'entry\'];
    $cb_lud_arrow_direction = $_POST[\'arrowdirection\'];

     //If the post value is \'up\', do this. If \'down\', do this.      
    if ($cb_lud_arrow_direction == \'up\') {
        $wpdb->query(\'UPDATE \'.$cb_lud_table.\' SET up_votes=up_votes+1
        WHERE entry_ID=\'.$cb_lud_entry_id.\'\');
    }

    else if ($cb_lud_arrow_direction == \'down\') {
        $wpdb->query(\'UPDATE \'.$cb_lud_table.\' SET down_votes=down_votes+1
        WHERE entry_ID=\'.$cb_lud_entry_id.\'\');
    }

die(); // this is required to return a proper result
}


//Create the function that executes the AJAX Callback
function cb_lud_arrow_callback(){
    }

/*
CREATE THE FORM
*/
//Create the form to allow users to add records
    $cb_lud_sc_form = \'
        <form id="list-up-down-form" name="list-up-down-form" action="" method="post">
        <table border="0">
            <tr>
//Using inputs rather than links because inputs can contain values.
                <td><h2>\'.$cb_lud_field1_name.\':</h2><input id="field1_input" name="field1_input" type="text"></input></td>
                <td><h2>\'.$cb_lud_field2_name.\':</h2><input id="field2_input" name="field2_input" type="text"></input></td>
                <td valign="bottom"><input name="add_record" type="submit" value="Add Record" /></td>
            </tr>
        </table>
        </form>
        \';

/*
DEFINE HOW THE FORM HANDLES THE INPUT(S)
*/
$field1_data = htmlspecialchars($_POST[\'field1_input\'], ENT_QUOTES);
$field2_data = htmlspecialchars($_POST[\'field2_input\'], ENT_QUOTES);
$up_votes = 0;
$down_votes = 0;
$new_data = array(
    $cb_lud_field1_name => $field1_data,
    $cb_lud_field2_name => $field2_data,
    \'up_votes\' => $up_votes,
    \'down_votes\' => $down_votes,
    );
$format = array(\'%s\', \'%s\', \'%f\', \'%f\');

if (isset($field1_data) && !empty($field1_data) && isset($field2_data) &&!empty($field2_data)) {
    $wpdb->insert(
        $cb_lud_table, $new_data, $format
    );
}

/*
DISPLAY THE LIST
*/          
//Get the list from the database, and set the variables for display in the output.
$get_list = $wpdb->get_results(\'SELECT entry_ID, \'.$cb_lud_field1_name.\' AS "field1", \'.$cb_lud_field2_name.\' AS "field2", up_votes, down_votes, up_votes - down_votes AS "total_votes"
    FROM \'.$cb_lud_table.\'
    GROUP BY entry_ID
    ORDER BY total_votes DESC
    \',OBJECT);

//Check if list is null, and if so, set a variable to display a warning. Otherwise, display the list.
if (empty($get_list)) {
    $cb_lud_sc_output .= "<em>Warning: You don\'t seem to have any records for this list. Why don\'t you add some now?</em>";
    $cb_lud_sc_output .= $cb_lud_sc_form;
    return $cb_lud_sc_output;
}
else {
    $cb_lud_sc_output .= $cb_lud_sc_form;
    $cb_lud_sc_output .= \'</br>\';
    $cb_lud_sc_output .= \'<table id="cb_lud_list" border="1" cellpadding="10">\';
    $cb_lud_sc_output .= \'<tr><td align="center"><strong><a id="sort-by-field1" href="">\'.$cb_lud_field1_name.\'<a></strong></td><td align="center"><strong>\'.$cb_lud_field2_name.\'</strong></td><td align="center"><strong>Score</strong></td><td align="center"><strong>Vote Up/Down</strong></td></tr>\';
        foreach ($get_list as $list_items) {
            $cb_lud_sc_output .= \'<tr class="line-items-rows"><td>\'.stripslashes($list_items->field1).\'</td><td>\'.stripslashes($list_items->field2).\'</td><td>\'.$list_items->total_votes.\'</td><td><form id="up-down-arrows-form" action="" method="post"><input class="up-arrow" name="arrow-up-ID-\'.$list_items->entry_ID.\'" type="image" src="\'.$cb_lud_upimg.\'" value="\'.$list_items->entry_ID.\'"/>&nbsp;<input class="down-arrow" name="arrow-down-ID-\'.$list_items->entry_ID.\'" type="image" src="\'.$cb_lud_downimg.\'" value="\'.$list_items->entry_ID.\'"/></form></td></tr>\';
            }
    $cb_lud_sc_output .= \'</table>\';
    return $cb_lud_sc_output;
}
};
/*
END SHORTCODE
*/

2 个回复
最合适的回答,由SO网友:Rutwick Gangurde 整理而成

您可能应该编写一个插件,它具有shortcode功能。您可以在插件中分离AJAX/jQuery代码,但不能在短代码中分离。

SO网友:MCG

你有没有试过把它放在Shortcode函数中?我建议:

function my_shortcode() {

?>
  <script>
    alert(\'test\')
  </script>
<?php

}
add_shortcode( \'my_shortcode\', \'my_shortcode\');

结束