2

I'm trying to make a menu that automatically populates from a custom post type I have and I'm having some trouble getting it right If someone could point me in the right direction I would greatly appreciate it. Here is the code. The PHP in the <img src> is pulling the right info and sticking it in the right spot, the_permalink pulls the correct url but then it is putting the url above the <li> tag instead of in the href.

<ul class="product-menu">
              <?php
              $products = new WP_Query(
                $args = array(
                  'post_type' => 'product',
                  'post_status' => 'publish',
                )
              );
              while ( $products->have_posts() ) {
                $products->the_post();
                $post_thumbnail_id = get_post_thumbnail_id();
                $post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
                echo 
                '<li>
                  <a href="' . the_permalink() . '">
                    <img src="' . $post_thumbnail_url . '" alt="' . get_the_title() . '">
                  </a>
                </li>';
              } 
              /* Restore original Post Data */
              wp_reset_postdata();?>
              </ul>
5

the_permalink() prints url immediately and returns nothing, you should use get_the_permalink() function, which returns current post url.

  • Thank you so much. I knew it was something incredibly simple, just couldn't get there for some reason. – mrben522 Jan 21 '16 at 15:06
3

You were using the_permalink which echos out, so you echoed out in an echo. You want to sue get_the_permalink to return the url which can then be echoed out into the code. Most wordpress functions starting with the_ directly echo out onto the page, those with get_ return the result.

This should work for you. I've also used the_post_thumbnail to bring out a wordpress formatted thumbnail image and update the issue with the hyperlink.

<ul class="product-menu">
    <?php

    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
    )

    $products = new WP_Query($args);

    while ( $products->have_posts() ) {
        $products->the_post();

        echo '<li><a href="' . get_the_permalink() . '">';

        // check if the post has a Post Thumbnail assigned to it.
        if ( has_post_thumbnail() ) {
            the_post_thumbnail();
        }

        echo '</a></li>';
    } 
    /* Restore original Post Data */
    wp_reset_postdata();

    ?>
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.