通过自定义帖子类型在帖子页面上进行AJAX搜索


8

我在单个帖子页面上创建ajax搜索时遇到问题。我需要将搜索结果限制为自定义帖子类型“ fod_videos”和“ post”以及类别12。我的问题是搜索将返回这些过滤器下的所有帖子,并且不采用搜索值。我猜想我遗漏了一些明显的东西,但我无法弄清楚。这是我的设置。

<div class="panel">
  <h2>Search Videos</h2>
  <div id="my-search">
   <form role="search" method="get" id="searchform" action="http://myurl.com/" >
    <input type="text" value="" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="Search" />
   </form>
  </div>
</div>

add_action('wp_ajax_wpa5000_search', 'wpa5000_search');
add_action('wp_ajax_nopriv_wpa5000_search', 'wpa5000_search');
function wpa5000_search(){
  global $wp_query;
  $search = $_POST['search_val'];
  $args = array(
    's' => $search,
    'posts_per_page' => 10,
    'cat' => 12, 
    'post_type' => array( 'post','fod_videos'  )
  );
  $wp_query = new WP_Query( $args );

  get_template_part( 'video-search-results' );

  exit;
}

add_action( 'wp_enqueue_scripts', 'wpa56343_scripts', 100 );
function wpa56343_scripts() {
 wp_enqueue_script(
    'wpa56343_script',
    get_template_directory_uri() . '/libs/search.js?ver=1.0',
    array( 'jquery' ),
    null,
    false
 );
 wp_localize_script(
    'wpa56343_script',
    'WPaAjax',
    array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    )
 );
}

// search.php

$(document).ready(function($){
 $('#searchsubmit').click(function(e){
    var $panel = $(this).closest(".panel");
    $panel.empty();
    e.preventDefault();
    var search_val=$("#s").val();
    $.post(
        WPaAjax.ajaxurl,
        {
            action : 'wpa5000_search',
            search_val : search_val
        },
        function( response ) {
            $panel.append( response );
        }
    );
 });
});

//video-search-results.php

<?php
 while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
   //STUFF
<?php endwhile; ?>

$ wp_query是实际的WP_Query对象吗?
Brian Fegter

@BrianFegter我不确定我明白你的意思。您知道我在索引页面上使用此确切公式来获取Ajax搜索结果很奇怪,并且效果很好。它只是没有拉search_val。我尝试打印$ search,但它什么也没有返回。
Pollux Khafra 2012年

1
AJAX操作未定义$ wp_query,因为除$ _POST数据外没有其他上下文。
Brian Fegter

在我的索引页面上如何工作?我用它用搜索结果替换默认循环,并且可以正常工作。
Pollux Khafra 2012年

Answers:


7

代替'cat' => 12$wp_query使用'category_name' => slugget_posts()

这是一个基本示例,它如何工作:

的PHP

add_action( 'wp_loaded', array ( 'T5_Ajax_Search', 'init' ) );

/**
 * Ajaxify the search form.
 */
class T5_Ajax_Search
{
    /**
     * The main instance. You can create further instances for unit tests.
     * @type object
     */
    protected static $instance = NULL;

    /**
     * Action name used by AJAX callback handlers
     * @type string
     */
    protected $action = 't5_ajax_search';

    /**
     * Handler for initial load.
     *
     * @wp-hook wp_loaded
     * @return void
     */
    public static function init()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    /**
     * Constructor. Registers the actions.
     *
     *  @wp-hook wp_loaded
     *  @return object
     */
    public function __construct()
    {
        $callback = array ( $this, 'search' );
        add_action( 'wp_ajax_'        . $this->action,        $callback );
        add_action( 'wp_ajax_nopriv_' . $this->action, $callback );
        add_action( 'wp_enqueue_scripts', array ( $this, 'register_script' ) );
    }

    /**
     * Callback for AJAX search.
     *
     * @wp-hook wp_ajax_t5_ajax_search
     * @wp-hook wp_ajax_nopriv_t5_ajax_search
     * @return void
     */
    public function search()
    {
        $args  = array ( 's' => $_POST['search_term'] );
        $args  = apply_filters( 't5_ajax_search_args', $args );
        $posts = get_posts( $args );
        if ( $posts )
        {
            $this->render_search_results( $posts );
        }
        else
        {
            print '<b>nothing found</b>';
        }
        exit;
    }

    /**
     * Create markup from $posts
     *
     * @param array $posts Array of post objects
     * @return void
     */
    protected function render_search_results( $posts )
    {
        print '<ul class="t5-ajax-search-results">';

        foreach ( $posts as $post )
        {
            printf(
                '<li><a href="%1$s">%2$s</a></li>',
                get_permalink( $post->ID ),
                esc_html( $post->post_title )
            );
        }
        print '</ul>';
    }

    /**
     * Register script and local variables.
     *
     * @wp-hook wp_enqueue_scripts
     * @return void
     */
    public function register_script()
    {
        wp_enqueue_script(
            't5-ajax',
            #plugins_url( __FILE__ ) . '/search.js',
            plugins_url( 'search.js', __FILE__ ),
            array ( 'jquery' ),
            NULL,
            TRUE
        );

        wp_localize_script(
            't5-ajax',
            'T5Ajax',
            array(
                'ajaxurl' => admin_url( 'admin-ajax.php' ),
                'action'  => $this->action
            )
        );
    }
}

的JavaScript search.js

jQuery( function( $ ) {
    // search filed
    var $s = $( '#s' );
    // the search form
    var $sForm = $s.closest( 'form' );
    console.log( $sForm );
    $sForm.on( 'submit', function( event) {
        event.preventDefault();
        $.post(
            T5Ajax.ajaxurl,
            {
                action:     T5Ajax.action,
                search_term: $s.val()
            },
            function( response ) {
                // just append the result to the search form.
                $sForm.append( response );
            }
        );
    });
});

限制搜寻

add_filter( 't5_ajax_search_args', 'restrict_t5_search' );

function restrict_t5_search( $args )
{
    $args['post_type'] = array ( 'post', 'fod_videos' );
    $args['category_name']       = 'category-slug';
    return $args;
}

除了我自己,$this->render_search_results( $posts );您还可以从主题中加载模板并$posts以更复杂的结果使用数组。:)


3

我得到了原始代码,但是使用了自定义帖子类型(没有类别)。在您的表单中添加一个隐藏的输入,并添加您的帖子类型,如下所示:

<input type="hidden" name="post_type" value="fod_videos" />
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.