Home Forums General Issues Creating conditional page link


Creating conditional page link

  • Hi,

    I have two CPTs that relate to each other – introduction and worksheet. I have over 60 introductions and eventually will have a worksheet for each one, but at the moment I only have a couple of worksheets.

    I’ve added a “worksheet link” custom field to the “em>introduction CPT using the Page Link option.

    I’ve created an archive page for my introduction CPT that displays all of its custom fields. I’d like to make the “worksheet” field conditional and only appear when a worksheet has been selected from the Page Link field.

    Where there is no corresponding worksheet and so the link doesn’t exist, I’d like there to be no link showing.

    Using the standard code:

    <a href="<?php the_field('worksheet_link'); ?>">Go to Worksheet</a>

    … I end up with links at the bottom of every item on the archive age, even where there is no worksheet. The dummy links just take me up to the top of the archive page.

    I found an alternative conditional statement:

    <?php if (the_field('worksheet_link') || get_field('worksheet_link')); ?>

    … which renders a link only on the introductions that have a worksheet. However, when I try to wrap it as a hyperlink:

    <a href="<?php if (the_field('worksheet_link') || get_field('worksheet_link')); ?>" >Go to Worksheet</a>

    … I have the same problem as with the first code – dummy links appear on every introduction, not just those with a worksheet. Somehow, the hyperlink appears to break the conditional statement.

    Can you suggest how to write the conditional code and wrap it as a hyperlink without ending up with these dummy links?

    Thanks in advance!

    Fantastic plugin. It’s saved me hours of slogging to create CPTs by hand. Thank you so much.

  • Hi @hastingsgull,

    try <?php if(get_field('worksheet_link')){the_field('worksheet_link');} ?>


  • Hi, thank you for this,

    It works much as the second and third options do already – that is – as long as it’s not wrapped in a hyperlink it shows only on those introductions that have a worksheet. Once I wrap the if statement with href:

    <a href="<?php if(get_field('worksheet_link')){the_field('worksheet_link');} ?>">Go to Worksheet</a>

    …it appears on all the introductions again.

    Any other ideas?

  • Hi @hastingsgull

    Why not:

    <?php if(get_field('worksheet_link')): ?>
    	<a href="<?php the_field('worksheet_link'); ?>">Go to Worksheet</a>
    <?php endif; ?>


  • Thank you, Elliot! Works like a dream.
    Sorry for the delay in replying. I’ve only just seen your post.

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Creating conditional page link’ is closed to new replies.