pop-up lighbox with AJAX

时间:2016-06-13 作者:Wordpress Student

我需要创建一个ajax脚本,用户在其中选择一个帖子类型,然后选择在灯箱或任何东西上显示帖子类型,但不加载。我想不出来。请给我一个想法来改进这个脚本。

<select>
 <?php
    $args = new WP_Query(array(
        \'post_type\' => \'post\'
    ));
 while($args->have_posts() ) : $args->the_post() ?>
  <option value="volvo"><?php the_title(); ?></option>

  <?php endwhile; ?>
</select> 

1 个回复
SO网友:Jeffrey von Grumbkow

要在WordPress网站中使用AJAX,您可以通过管理AJAX。php文件。此文件处理您的请求并将其发送到正确的函数。

关于如何实现以下目标的简短分步指南:

首先,您需要本地化javascript文件,以便它知道管理ajax的URL。服务器上的php文件。

add_action( \'wp_enqueue_scripts\', \'wpse_229573_localize\' );
function wpse_229573_localize() {
    wp_localize_script( \'FILE_HANDLER\', \'ajax\', array( \'url\' => admin_url( \'admin-ajax.php\' ) ) );
}
其中FILE\\u HANDLER是将脚本排入队列时使用的句柄。

现在,在这个javascript文件中,您可以用不同的方式进行AAX调用,下面是一种可能性

jQuery.ajax( {
    url: ajax.url, //The ajax object is populated in this script thanks to the wp_localize_script function. ajax.url containts the url to your admin-ajax.php file.
    type:\'POST\',
    data: {
        action: \'wpse_229573_ajax_callback\', // This action is important as it determines which functions are called
        post_type: jquery( \'#post-type\' ).val(), // Here you can send the post type set by the visitor, this would be a <select> with id="post-type" for example
    },
    success: function( data ) {
        // On a succesful return \'data\' contains whatever you have echoed in the ajax function
        console.log( data );
        // Here you can manually open a lightbox with the correct data if you want, for the correct code to you that you need to check the documentaiton of your chosen lightbox plugin
    }
});
在任何PHP文件中,理想情况下都是一个插件,但它可以是您的functions.php 此外,您还为WordPress添加了一个操作来处理AJAX调用。您需要两个,一个用于管理员,另一个用于非管理员(否则,如果假设您想要测试,并且您以管理员身份登录,那么它将不起作用)

// Notice the wpse_229573_ajax_callback after both wp_ajax and wp_ajax_nopriv
// These correspond with the action you\'ve set in the javascript file making the AJAX call. 
// This is how WordPress knows what PHP code to run on the AJAX call.
add_action( \'wp_ajax_wpse_229573_ajax_callback\', \'wpse_229573_ajax_function\' );
add_action( \'wp_ajax_nopriv_wpse_229573_ajax_callback\', \'wpse_229573_ajax_function\' );

// This is the function that both actions above call
// The data that you\'ve send in the AJAX call is availble as either $_POST or $_GET depending on the call
// In this example it\'s $_POST
function wpse_229573_ajax_function() {
    // We added post_type to the AJAX call as data, now we\'re echoing that back.
    // You can also choose to json_encode() data before you echo and parse the JSON in your javascript file.
    echo $_POST[\'post_type\'];
    wp_die();
}

相关推荐

尝试在WordPress中实现AJAX注释,遇到WP错误

我试图在WordPress中为我的评论实现Ajax,使用this tutorial. 但我在将教程中的代码集成到自己的预构建主题时遇到了问题。问题是,我要么得到一个WP错误“检测到重复注释;看来你已经说过了!”或标准500错误。以下是我得到的:下面是我对ajax的评论。js文件如下所示: * Let\'s begin with validation functions */ jQuery.extend(jQuery.fn, { /* * check i