Search code examples
phpwordpresswordpress-themingcustom-post-type

Custom Post Type Inside Regular Post Type


I am working on a website in Wordpress where I need to use custom posts (which I already created with the help of a plugin).

The problem is that the theme that I use allows me to display the post on the page organized according to categories, but when I create a custom post and put it into a category it is not displayed on the web (as if I had never created the post) but if I create the same post from the normal page of Wordpress entries (a standard Wordpress post type) and I put it in the same category this is shown on the page. Also, when I enter the custom post page the entry I created appears but when I enter the normal entries page it does not appear.

I went to a portal where they said how to add the custom post to the Wordpress categories by writing some lines of code in the functions.php file but this did not work, now I see the custom post within the category page but I still do not see them inside of the Wordpress entries page and also still not shown on the web.


Solution

  • You need to create a custom query. This page has good explanations and examples: https://codex.wordpress.org/Class_Reference/WP_Query

    The most important thing in your case is to include this in your arguments array, which selects posts and your CPT:

    'post_type' => array('post', 'your-custom-posttype'),
    

    and also this which filters by category:

    'category_name' => 'your_category_name'
    

    So a typical simple custom query would look like this:

    $args = array(
        'post_type' => array('post', 'your-custom-posttype'),
        'category_name' => 'your_category_name',
        'post_status' => 'publish',
        'posts_per_page' => 12
    );
    $query1 = new WP_Query( $args );
    
    if ( $query1->have_posts() ) {
        while ( $query1->have_posts() ) {
            $query1->the_post();
            echo '<li>' . get_the_title() . '</li>';
            // Other stuff echoing content etc. to be added here.....
        }
        wp_reset_postdata();
    }