Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning to Display Posts by Taxonomy?

Tags:

php

wordpress

Here is the situation, I have a custom tax called Skill. I want to be able to display posts only with skill set as Japanese from English.

I am trying to learn how to use pre_get_posts hook to modify my get_posts query. Here is my example, however I land with the error:

Notice: Undefined variable: postdata

This is what I have tried based on research:

add_filter( 'pre_get_posts', 'wpshout_fundraiser_recent_posts' );
function wpshout_fundraiser_recent_posts( $query ) {

    // Fetch only posts tagged with "Japanese from English"
    $taxquery = array(
        array(
            'taxonomy' => 'Japanese from English',
            'field' => 'skill',
            'terms' => array( 'skill' ),
        )
    );
    $query->set( 'tax_query', $taxquery );

I am sure something is wrong with the above query, which I don't fully understand. Any help and please explain what each field of the array is for if possible.

like image 468
Elevant Avatar asked Apr 11 '17 06:04

Elevant


People also ask

How do I find the taxonomy of a WordPress post?

php // get taxonomies terms links function custom_taxonomies_terms_links() { global $post, $post_id; // get post by post id $post = &get_post($post->ID); // get post type by post $post_type = $post->post_type; // get post type taxonomies $taxonomies = get_object_taxonomies($post_type); $out = "<ul>"; foreach ($ ...

How do I display custom post category wise in WordPress?

Now, if you want to display all your posts from a specific category on a separate page, WordPress already takes care of this for you. To find the category page, you simply need to go to Posts » Categories » View page and click on the 'View' link below a category.


1 Answers

Try this below code this should work,

add_filter( 'pre_get_posts', 'wpshout_fundraiser_recent_posts' );
function wpshout_fundraiser_recent_posts( $query ) {

$posts_array = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type' => 'Your Post Type Name',
        'tax_query' => array(
            array(
                'taxonomy' => 'Japanese from English',
                'field' => 'skill',
                'terms' => array( 'skill' ),
            )
        )
    )
);
return $posts_array;

}
like image 83
Prabu Avatar answered Sep 25 '22 09:09

Prabu