user3170187
user3170187

Reputation: 15

Merging PHP codes

I want to combine 1 part of my PHP code into another part, and I can't seem to figure out how to do it.

This is the code:

        <?php
        if (is_single()) {
            while (have_posts()) : the_post();
                // get thumbnail
                wikiwp_get_thumbnail($post);
        ?>
<div>This should stay here in a post</div>
<div>And this should also be visible in this case</div>


       <?php
            endwhile;
        } else {

        ?>

<div>This should stay here in a page</div>

        <?php
        } 
        ?>

I want to add the first bit of php into the endwhile. I want to put this bit:

                <?php
                if (is_page()) {
                    while (have_posts()) : the_post();
                        // get thumbnail
                        wikiwp_get_thumbnail($post);
                ?>

into this part: (without breaking the code)

           <?php
                endwhile;
            } else {

            ?>

The result is: If its a single post it will show:

[thumbnail] 
This should stay here 
And this should also be visible in this case

If its a page it will show:

[thumbnail] 
This should stay here on a page

Upvotes: 1

Views: 50

Answers (2)

peixotorms
peixotorms

Reputation: 1283

How about this?

<?php

if (is_single() || is_page()) {
    while (have_posts()):
        the_post();

        # page + post
        wikiwp_get_thumbnail($post);

        # post only
        if (is_single()) {
?>

<div>This should stay here in a post</div>
<div>And this should also be visible in this case</div>

<?php
        } else if (is_page()) {
?>

<div>This should stay here in a page</div>

<?php
        }
    endwhile;
} else {
?>

<div>This is neither a page or post!</div>
<?php
}
?>

Upvotes: 1

random_user_name
random_user_name

Reputation: 26160

The code you have provided, merged together, would look like this:

<?php
    if (is_single()) {
        while (have_posts()) : the_post();
            // get thumbnail
            wikiwp_get_thumbnail($post);
?>
            <div>This should stay here in a post</div>
            <div>And this should also be visible in this case</div>
<?php
        endwhile;
    } else {
        if (is_page()) {
            while (have_posts()) : the_post();
            // get thumbnail
            wikiwp_get_thumbnail($post);
?>
            <div>This should stay here in a page</div>
<?php
        }
    } 
?>

Note that this will not output anything if it's not a single post or a page.

Upvotes: 0

Related Questions