How can I remove the post from subcategory 1.2 on subcategory 1?
Use the 'category__in'
argument parameter instead of the 'cat'
parameter.
Here is a user function that does what you want.
/**
* Category post list.
*
* An unordered list of category posts links. Posts in subcategories
* are not listed in parent category. Skips categories with no posts.
*
* @param $parent_category The parent category to start with. Defaults to 0.
*/
function wpse_113987_category_post_list( $parent_category = 0 ) {
$post_list_format="<li><a href="https://wordpress.stackexchange.com/questions/113987/%s">%s</a></li>";
// Step through each category object.
foreach ( get_categories( "child_of=$parent_category" ) as $category ) {
$category_posts = get_posts( array(
// Do not include posts in sub categories.
'category__in' => array( $category->term_id ),
) );
// Skip categories with no posts.
if ( empty( $category_posts ) )
continue;
echo "<h2>$category->name</h2>\n";
echo "<ul>\n";
// Step through each post object.
foreach ( $category_posts as $post ) {
printf( $post_list_format, get_permalink( $post->ID ), get_the_title( $post->ID ) );
}
echo "\n</ul><!-- end $category->name -->\n";
}
}
To call it, use:
wpse_113987_category_post_list( 4 );