David
David

Reputation: 21

Dynamically link to child page WordPress

I'm using subpages on a WP site as follows;

Products (Parent Page) -Office (Subpage 1) --Office Gallery (Child of Subpage 1) -School (Subpage 2) --School Gallery (Child of Subpage 2) ....etc

How can I create a link on each subpage to its child page using just one template in my theme? I need to be able to give this link a css class name. In other words I need to have the code in my page template look something like:

<a class="gallery-button" href="RETURN LINK TO CHILD PAGE OF CURRENT PAGE"></a>

or something like that......

I tried using wp_list_pages for a child page from the WordPress Codex but this returns a list and I really need just the permalink to the child page.

Is this easy? Impossible?

Thanks in advance.

Upvotes: 1

Views: 3371

Answers (2)

Ricky Irvine
Ricky Irvine

Reputation: 11

Here's a revision of TheDeadMac's code I ended with that works in WP 3.9:

$children = get_pages("child_of=".$post->ID."&sort_column=menu_order");
$first_child = $children[0];
$first_child_permalink = get_permalink($first_child->ID);
echo '<a href="' . $first_child_permalink . '">Link Text</a>';

Upvotes: 1

TheDeadMedic
TheDeadMedic

Reputation: 9997

You'll need to query posts to get the first child of the post in question;

<?php
    if ($children = get_children('post_type=page&numberposts=1')) {
        $first_child = $children[0];
        $first_child_permalink = get_permalink($first_child->ID);
        echo '<a class="gallery-button" href="' . $first_child_permalink . '">Link Text</a>';
    }
?>

Upvotes: 1

Related Questions