WordPress Custom Type Posts next previous join table

I am working in WordPress and I need to display the next and previous links on a custom type posts.

I need to list all the custom post types on post_town which is in a table

Read More

cus_builders

ID     post_town    post_type 
-----------------------------------

123    Manchester   cus_builders

The below code gives me all custom posts cus_builders, and I only want the builders in Manchester.

// get_posts in same custom taxonomy
$postlist_args = array(
'posts_per_page' => -1,
'post_type' => 'cus_builders',
'post_town' => 'Manchester' 
);
$postlist = get_posts( $postlist_args );

How to join the query on table cus_builders so it only gives me back based on cus_builder.post_town?

Related posts

Leave a Reply

1 comment

  1. It’s not clear what you’re after, but here are two guesses:

    1) If the user input is $post_town:

    // Input:
    $post_town = 'Manchester'; 
    
    // Query:
    $postlist_args = array(
        'posts_per_page' => -1,
        'post_type'      => get_post_type_by_town( $post_town ),
        'tax_query'      => array(
             array( 
                 'taxonomy' => 'post_town',
                 'terms'    => sanitize_key( $post_town ),
                 'field'    => 'slug',
             ),
        ),
    );
    $postlist = get_posts( $postlist_args );
    

    where

    function get_post_type_by_town( $post_town )
    {
        global $wpdb;
        $sql = "SELECT post_type FROM cus_builders WHERE post_town = '%s'";
        return $wpdb->get_col( $wpdb->prepare( $sql, $post_town ) );
    }
    

    This setup would require multiple custom post types, sharing the same custom taxonomy post_town.

    2) If the user input is $post_type:

    // Input:
    $post_type = 'cus_builders'; 
    
    // Query:
    $postlist_args = array(
        'posts_per_page' => -1,
        'post_type'      => $post_type,
        'tax_query'      => array(
             array( 
                 'taxonomy' => 'post_town',
                 'terms'    => get_post_towns_by_post_type( $post_type ),
                 'field'    => 'slug',
             ),
        )
    );
    $postlist = get_posts( $postlist_args );
    

    where:

    function get_post_towns_by_post_type( $post_type )
    {
        global $wpdb;
        $sql = "SELECT post_town FROM cus_builders WHERE post_type = '%s'";
        return $wpdb->get_col( $wpdb->prepare( $sql, $post_type ) );
    }
    

    This setup requires a custom taxonomy post_town.


    It’s in general a good idea to avoid capitals, spaces and special characters when working with slugs.