web-dev-qa-db-fra.com

Comment mettre JQuery/Ajax dans shortcode?

Le but de ce plugin est de créer une liste que les utilisateurs peuvent modifier avec des votes à la hausse ou à la baisse. Le shortcode est censé afficher la liste sur une page et utiliser JQuery pour fadeIn et fadeOut lors de la mise à jour de la base de données.

Une démonstration du concept est disponible sur http://bucketlingerwedding.com/80s-music-reception/ (note: le code de travail n'est pas encore utilisé AJAX).

Je voudrais mettre ce plugin dans le référentiel Wordpress, mais le AJAX me tue. Ce qui suit est le dernier code. Il montre seulement une page avec une zone de contenu vide. Je dois obtenir ce code pour mettre à jour la base de données avec AJAX et éviter de recharger la page afin de pouvoir travailler dans des animations/transitions.

Le code est commenté pour refléter ma compréhension de ce que j'essaie de faire.

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
*/
1
ChrisBuck

Vous devriez probablement écrire un plugin, qui a la fonction shortcode. Vous pouvez séparer le code AJAX/jQuery dans un plugin, mais pas dans un shortcode.

1
Rutwick Gangurde

ave vous avez essayé de le mettre dans la fonction Shortcode? Je suggérerais ceci:

function my_shortcode() {

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

}
add_shortcode( 'my_shortcode', 'my_shortcode');
0
MCG