简体   繁体   中英

Wordpress wp query for custom post type category

I am working on pagination in WordPress, pagination working fine for all posts, But I need posts based on category

Now I am using this query for getting all post

$per_page = 8;
$start = $page * $per_page;
$page = sanitize_text_field($_POST['page']);

$wpdb->get_results($wpdb->prepare("
        SELECT * FROM " . $table_name . " WHERE post_type = 'articles' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page ));

Can anyone tell me how to display post based on category, I am using custom post type('articles').

Thanks

I have tried with this that is working with me.You may help this code.

Here, you have to join some tables to get post based on category. For that I used join in query.You are using ajax and you will get category_name in POST and that will be assign to related table.

Updated:

$per_page = 8;
$start = $page * $per_page;
$page = sanitize_text_field($_POST['page']);

$category_name = $_POST['category_name'];

$wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->posts   
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->terms.name = ''
AND $wpdb->term_taxonomy.taxonomy LIKE '%".$category_name."%'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'articles' 
ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM