php – Is there a way to create two template for single custom post type page?

Question

This is a strange task but I really faced with it. On the home page there is loop for showing all custom post type. And I need to have oportunity when user click to the cpt link from the home page display one type of the single page. And if user go to the custom post type from inner page show other single custom post type template. I found old answer about this on the stackoverflow
But it does not work properly. The code from stackoverflow:

On the home page I added to the link something like this:

<a href="<php the_permalink();?>?template=gallery"> Gallery Page </a>

And in the custom post type single page add this chunk of code:

if($_POST['template'] == 'gallery') {
    get_template_part('single', 'gallery'); // the file for this one is single-gallery.php
 }elseif($_POST['template'] == 'other'){
   get_template_part('single', 'other'); // the file for this one is single-other.php
 }

At first glance, this makes sense, but it doesn’t work. Please help to solve this.

in progress 0
Victor Sokoliuk 7 months 2022-01-04T00:54:06-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2022-01-07T01:46:41-05:00

    If you’re going this way, you should use $_GET and not $_POST. Because it looks like you are not making a post request.

    So:

    if ( isset($_GET['template']) && $_GET['template'] == 'gallery' ) {
    

    Other than that, you should open PHP with <?php instead of <php.

Leave an answer

Browse
Browse