After having a really good chat that taught me a lot with janh2 we have come up with this solution that got rid of the issue. Read trough the chat to learn from my mistake(s).
Instead of going about it the way I did use this approach, much less code and it will work on the live server also.
Since WP automatically looks for a category-$slug.php
file if you are on an archive (category) page create a file named category.php
in the theme root folder. In that category.php
get the current category.
Since I have my category-photos.php
in the template-parts
folder I get the current category of the archive page and then use that to get the template for it from the template-parts
folder.
category.php
$current_category = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
$category_slug = $current_category->slug;
get_template_part('template-parts/category', $category_slug);
category-photos.php
$args = array(
'category_name' => 'photos',
'post_type' => 'post'
);
$query = new WP_Query($args);
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
the_title();
the_content();
endwhile;
endif;
wp_reset_postdata();
Since static and other pages use index.php
if there are no other template files I can write this code below in there. I understand that once there is a category-$slug.php
or page-$slug.php
WordPress will automatically use that. Again since I have my page templates in folder template-parts
I only need this in index.php
and be done with it.
index.php
get_header();
$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
$pagename = $current_page->post_name;
get_template_part( 'template-parts/page', $pagename );
get_footer();
For reference, I use this answer for getting the queried object with the correct data.