【问题标题】:Get First Post Using Category Slug Wordpress使用 Category Slug Wordpress 获取第一篇文章
【发布时间】:2023-03-09 19:10:01
【问题描述】:

我有一个 ajax 调用,应该在 onclick 类别中显示第一个自定义帖子。我的代码似乎设置正确,但我似乎无法得到帖子。这是我的代码:

add_action( 'wp_ajax_nopriv_load-products-default', 'prefix_load_default_cat_posts' );
add_action( 'wp_ajax_load-products-default', 'prefix_load_default_cat_posts' );
function prefix_load_default_cat_posts(){

   $slug = $_POST['cat'];

//    echo $slug;

   $args = array(
       'post_type' => 'products',
       'posts_per_page' => 1,
       'category_name' => $slug
   );

    $q = new WP_Query($args);

    if( $q->have_posts()):
        while( $q->have_posts()):

            $q->the_post();

            echo 'post here';

        endwhile;
    endif;

    die();
}

?>

【问题讨论】:

  • 这段代码有错误吗?
  • 没有错误,只是没有得到回应。我在下面回答了我自己的问题,谢谢!

标签: php ajax wordpress loops


【解决方案1】:

是的,所以我的代码设置不正确...这是在自定义类别中获取第一个自定义帖子的正确方法:

add_action( 'wp_ajax_nopriv_load-products-default', 'prefix_load_default_cat_posts' );
add_action( 'wp_ajax_load-products-default', 'prefix_load_default_cat_posts' );
function prefix_load_default_cat_posts(){

   $slug = $_POST['cat'];

    //    echo $slug;

   $args = array(
       'post_type' => 'products',
       'posts_per_page' => 1,
       'order' => 'ASC',
       'tax_query' => array(
           array(
               'taxonomy' => 'brand',
               'field' => 'slug',
               'terms' => $slug
           ),
       ),
   );

   $q = new WP_Query($args);

   if( $q->have_posts()):

        while( $q->have_posts()):

            $q->the_post();

            the_title();

        endwhile;

   endif;   

    die();
}

?>

【讨论】:

    【解决方案2】:

    tax_query takes an array of tax query arguments arrays (it takes an array of arrays) but you are using only single array. The correct code is as following
    
    add_action( 'wp_ajax_nopriv_load-products-default', 
    
    'prefix_load_default_cat_posts' );
    
    add_action( 'wp_ajax_load-products-default', 'prefix_load_default_cat_posts' );
    
    function prefix_load_default_cat_posts(){
    
    $slug = $_POST['cat'];
    
    $categories = get_terms(array('tshirt'),array('hide_empty' => false));
    
          foreach( $categories as $cat )
    
           {   
    
            $args = array(
           'post_type' => 'products',
           'posts_per_page' => 1,
           'tax_query' => array( array('taxonomy' => 'tshirt','field' => 'slug', 
           'terms' => $slug)));
    
        $q = new WP_Query($args);
    
        if( $q->have_posts()):
    
            while( $q->have_posts()):
    
                $q->the_post();
    
                echo 'post here';
    
            endwhile;
    
        endif;
    
        
       }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多