使用Ajax

时间:2018-06-12 11:11:37

标签: php ajax wordpress custom-post-type custom-wordpress-pages

这个帖子会变得很长,请耐心等待我!

我正在尝试构建一个自定义页面,该页面将用作"目录"我在后端创建的两种帖子类型。

这就是我尝试构建的内容: enter image description here

到目前为止,我已经有了一个功能太大但它能完成工作(或至少差不多)。

所以我将首先发布HTML文件,然后分享我在自定义页面中使用的功能:

<?php 
/*
Template Name: Buscador Avanzado
Template Post Type: page
*/
?>
<?php get_header(); ?>
    <div class="container">
        <div class="row">
            <?php echo get_breadcrumb(); ?>     

<div id="my-adv-search">
<!-- Post Type -->
<div class="col-md-3">
    <div class="form-group">
        <label for="q_post_type">Tipo</label>
        <select class="form-control" id="q_post_type">
            <option selected>Selecciona una opcion</option>
            <?php
            $args = array(
                'public'    => true,
                '_builtin' => false,
            );
            $post_types = get_post_types($args);
                foreach( $post_types as $post_type ) {
                    echo '<option>' . $post_type . '</option>' ;    
                }
            ?>
        </select>
    </div>
</div>

<!-- Genero -->
<div class="col-md-3">
    <div class="form-group">
        <label for="q_taxonomy">Genero</label>
        <select class="form-control" multiple id="q_taxonomy">
            <option value="any" selected>Selecciona una opcion</option>
            <?php 
            $args = array(
              'public'   => true,
              '_builtin' => false
            ); 
            $output = 'names'; // or objects
            $operator = 'and'; // 'and' or 'or'
            $taxonomies = get_taxonomies( $args, $output, $operator ); 
            if ( $taxonomies ) {
              foreach ( $taxonomies  as $taxonomy ) {
                echo '<option>' . $taxonomy . '</option>';
              }
            }
            ?>
        </select>
    </div>
</div>

<!-- Estado -->
<div class="col-md-3">
    <div class="form-group">
        <label for="q_orderby">Estado</label>
        <select class="form-control" id="q_orderby">
            <option value="any" selected>Selecciona una opcion</option>
            <?php
            foreach ( [
              'author'        => 'Author',
              'comment_count' => 'Popularity (# of Comments)',
              //'year'          => 'Year',
              'en_emision'   => 'Emision',
              'en_final'   => 'Finalizado',
              //'views_count'   => 'Views',
              //'order'         => 'ASC ? DESC',
            ] as $value => $label ) {
              printf( '<option value="%s">%s</option>',
                esc_attr( $value ), esc_html( $label ) );
            }
            ?>
        </select>
    </div>
</div>


<!-- Year -->
<div class="col-md-3">
    <div class="form-group">
        <label for="q_year">Año</label>
        <select class="form-control" id="q_year">
            <option value="any" selected>Selecciona una opcion</option>
            <?php
            $args = array(
                'public'    => true,
                '_builtin'  => false,
                'type'      => 'yearly',
                'format'    => 'option',
            );
            wp_get_archives($args);
            ?>
        </select>
    </div>

</div>


<!-- Nonce field. -->
<?php wp_nonce_field( 'my-adv-search', 'q_nonce' ); ?>

<!-- Search Button -->
<div class="col-md-12">
    <input type="submit" class="btn btn-success" id="buscar_btn" value="Search">
    <br><br>
    <noscript><b>Tu buscador no soporta Javascript, haciendo imposible mostrar los posts.</b></noscript>
    <div id="resultados"><div class="cargando_medio"></div></div>
</div>
</div><!-- End #my-adv-search -->



        </div>
    </div>

<?php get_footer(); ?>
<script type="text/javascript">
jQuery( function( $ ){
    var ajaxurl = '/wptests/wp-admin/admin-ajax.php';

    function searchPosts( btn ) {
        var _btn_text = btn.value;//, q_order;

        btn.disabled = true;
        btn.value = 'Searching..';

//        q_order = $( '#q_order-asc' ).is( ':checked' ) ?
//            'ASC' : 'DESC';

        return $.post( ajaxurl, {
            action: 'my_adv_search',
            q_nonce: $( '#q_nonce' ).val(),
            q_post_type: $( '#q_post_type' ).val(),
            q_taxonomy: $( '#q_taxonomy' ).val(),
            q_year: $( '#q_year' ).val(),
            q_orderby: $( '#q_orderby' ).val(),
//            q_order: q_order,
        } ).done( function( s ){
            if ( 'session_expired' === s ) {
                location.reload();
                return;
            }

            $( '#resultados' ).html( s );
        } ).always( function(){
            btn.value = _btn_text;
            btn.disabled = false;
        } );
    }

    $( '#buscar_btn', '#my-adv-search' ).on( 'click', function( e ){
        e.preventDefault();

        // Run AJAX search.
        searchPosts( this );

        // Remove button focus.
        this.blur();
    } );
} );
</script>

现在这里有与它一起工作的功能(我指出了问题出在哪里):

// Buscador Avanzado
add_action( 'wp_ajax_my_adv_search', 'ajax_my_adv_search' );
add_action( 'wp_ajax_nopriv_my_adv_search', 'ajax_my_adv_search' );
function ajax_my_adv_search() {
    if ( ! check_ajax_referer( 'my-adv-search', 'q_nonce', false ) ) {
        echo 'session_expired';
        wp_die();
    }

    $post_type = isset( $_POST['q_post_type'] ) ? $_POST['q_post_type'] : '';
    $taxonomy = isset( $_POST['q_taxonomy'] ) ? $_POST['q_taxonomy'] : [];
    $year = isset( $_POST['q_year'] ) ? $_POST['q_year'] : '';
    $orderby = isset( $_POST['q_orderby'] ) ? $_POST['q_orderby'] : [];
    $order = isset( $_POST['q_order'] ) ? $_POST['q_order'] : '';

    // Note that if $post_type is 'any', all post statuses will be included. In
    // that case, you may want to set specific post statuses below.
    $post_status = 'publish';

    // by Taxonomy
    $taxonomy = array_filter( (array) $taxonomy );
    if ( ! in_array( 'any', $taxonomy ) ) {
        $taxonomy = array_unique( array_map( 'trim', $taxonomy ) );

        add_filter( 'posts_join', function( $c ) use ( $taxonomy ) {
            if ( ! empty( $taxonomy ) ) {
                global $wpdb;
                // 1 below is one/number and not the lowercase of L
                $c .= " INNER JOIN {$wpdb->term_relationships} AS ctr1 ON ctr1.object_id = {$wpdb->posts}.ID" .
                    " INNER JOIN {$wpdb->term_taxonomy} AS ctt1 ON ctt1.term_taxonomy_id = ctr1.term_taxonomy_id";
            }
            return $c;
        } );

        add_filter( 'posts_where', function( $c ) use ( $taxonomy ) {
            if ( ! empty( $taxonomy ) ) {
                $tax_list = array_map( 'esc_sql', $taxonomy );
                $tax_list = "'" . implode( "', '", $tax_list ) . "'";

                // 1 below is one/number and not the lowercase of L
                $c .= " AND ( ctt1.taxonomy IN ($tax_list) )";
            }
            return $c;
        } );
    }

    // by Custom Field Value - Metadata
    $orderby = array_filter( (array) $orderby );
    if ( in_array( 'any', $orderby ) ) {
        // Don't sort by post date.
        $orderby2 = false;
    } else {
        $orderby = array_unique( array_map( 'trim', $orderby ) );

        // TRUE if we're sorting by year.
        $ob_year = false;

        foreach ( $orderby as $i => $s ) {
            // Sort posts by year.
            if ( 'year' === $s ) {
                $ob_year = true;
                unset( $orderby[ $i ] );
            }
//// PROBLEM BEGINS HERE
            // Sort posts by meta value en_emision from meta key estado_de_video. Note that this would only return
            // posts that have the custom field 'en_emision'.
            if ( 'en_emision' === $s ) {
                $meta_key = 'en_emision';
                $orderby2 = 'meta_value';
                unset( $orderby[ $i ] );
            }

            // Sort posts by meta value en_final from meta key estado_de_video. Note that this would only return
            // posts that have the custom field 'en_final'.
            if ( 'en_final' === $s ) {
                $meta_key = 'en_final';
                $orderby2 = 'meta_value';
                unset( $orderby[ $i ] );
            }
        }

//// PROBLEM ENDS HERE
        add_filter( 'posts_orderby', function( $c, $q ) use ( $ob_year ) {
            if ( $ob_year ) {
                global $wpdb;

                // Use the value parsed by WP_Query.
                $order = $q->get( 'order' );

                $c .= $c ? ', ' : '';
                $c .= "YEAR({$wpdb->posts}.post_date) $order";
            }
            return $c;
        }, 10, 2 );

        $ok = isset( $orderby2 );
        if ( ! $ok && empty( $orderby ) ) {
            // Don't sort by post date.
            $orderby2 = false;
        } elseif ( ! $ok ) {
            // Pass to WP_Query as a string.
            $orderby2 = implode( ' ', $orderby );
        }
    }

    // by Year
    if ( ! is_numeric( $year ) ) {
        $year = '';
    }



    $q = new WP_Query( [
        'post_status' => $post_status,
        'post_type'   => array($post_type),
        'posts_per_page' => -1,
        'post_parent' => 0,
        'year'        => $year,
        'meta_key'    => isset( $meta_key ) ? $meta_key : '',
        'orderby'     => $orderby2,
        'order'       => $order,

    ] );

    if ( $q->have_posts() ) {
        echo '<ul>';
        while ( $q->have_posts() ) {
            $q->the_post();
            ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></li>
            <?php
        }
        echo '</ul>';
    } else {
        echo '<div class="alert alert-danger">Ningun Resultado</div>';
    }

    wp_die();
}

现在我想要的是按一个meta_key(estado_de_video)和我为该元键创建的两个meta_value(en_emision,en_final)排序。

现在使用上面的函数我尝试做类似的事情,就好像我按年份排序但是它没有用,然后我尝试稍微更改WP_Query:

有人试图帮助我这个建议:

$q = new WP_Query( [
        'post_status' => $post_status,
        'post_type'   => array($post_type),
        'posts_per_page' => -1,
        'post_parent' => 0,
        'year'        => $year,
        'orderby'     => 'meta_value', //SET THIS AS REQUIRED
        'order'       => $order,

    ] );
if ( isset( $meta_key ) && '' != $meta_key ) {
    $q['meta_key'] = 'estado_de_video';
    $q['meta_value'] = $meta_key;
}

因为我已经被告知这应该以某种方式解决,或者至少它应该返回带有meta_value(en_emision或en_final)的帖子,但它没有,然后我试图改变通过删除评论部分(参见上面的功能片段)并删除它来实现:

if ( isset( $meta_key ) && '' != $meta_key ) {
    $q['meta_key'] = 'estado_de_video';
    $q['meta_value'] = $meta_key;
}

因此,一旦删除了这些内容,我就尝试更改WP_Query:

$q = new WP_Query( [
        'post_status' => $post_status,
        'post_type'   => array($post_type),
        'posts_per_page' => -1,
        'post_parent' => 0,
        'year'        => $year,
        'orderby'     => 'meta_value', //SET THIS AS REQUIRED
//        'meta_key'    => $meta_key,
//        'meta_value'  => $meta_values,
        'order'       => $order,
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => 'estado_de_video',
                'value' => array('en_emision', 'en_final'),
                'compare'   => 'EXISTS'
            ),
        ),

] );

还没有成功。有人可以指导我,或者至少告诉我一个更好的方法吗?

提前致谢。

  

以下这个BLOCKQUOTE并不是必须提供帮助但是   如果有人决定,则表示赞赏。

我需要第二个<select>的帮助;我希望根据选择的帖子类型显示分类法。例如:

CPT的{p> <select> 1:Peliculas,

<select> 2:从选定的帖子类型中加载类别分类。

让我们说我选择了#34; Peliculas&#34;那么我希望自定义分类中所做的所有类别都附加在&#34; Peliculas&#34;。

现在我有两个CPT,一个叫做动漫,另一个叫做peliculas

&#34;动画及#34;有&#34; categorias_anime&#34;分类,

&#34; peliculas&#34;拥有&#34; categorias_movie&#34;分类

提前致谢。

1 个答案:

答案 0 :(得分:0)

按给定的meta_value排序很简单,不需要复杂的查询。 我看到你混淆了给定代码中的元键和值。

请使用:

$q = new WP_Query( [
        'post_status' => $post_status,
        'post_type'   => array($post_type),
        'posts_per_page' => -1,
        'post_parent' => 0,
        'year'        => $year,
        'orderby'     => 'meta_value',
        'meta_key' => 'estado_de_video',
        'order'       => $order, //ASC or DESC
    ] );

这就是全部。无需在此处设置meta_value参数。