WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Link post title to attachment page, if exist (2 posts)

  1. baalstorm
    Member
    Posted 1 year ago #

    Hello,
    i'd need to show a list of post title and, if the post has attachments, link the title to the attachment page. any help?

    i've managed to get the posts with attachment with this:

    $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'offset' => 0,
        'orderby' => 'menu_order',
        'order' => 'asc',
        'post_status' => null,
        'post_parent' => $post->ID,
        );
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            if(wp_attachment_is_image( $attachment->ID )) {
    echo '<a href="'. get_attachment_link($attachment->ID) . '">'. get_the_title() .'</a>';
    
            break;
        }
    }
    }

    how do i add an "else" to show just the title if the post has no attachments?

    thank you

  2. baalstorm
    Member
    Posted 1 year ago #

    ok, solved

    $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'offset' => 0,
        'orderby' => 'menu_order',
        'order' => 'asc',
        'post_status' => null,
        'post_parent' => $post->ID,
        );
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            if(wp_attachment_is_image( $attachment->ID )) {
    echo '<h1><a href="'. get_attachment_link($attachment->ID) . '">'. get_the_title() .'</a></h1>';
    
            break;
        } 
    
    }
    
    }
    else {
    echo '<h1>'. get_the_title() .'</h1>';
    };

Topic Closed

This topic has been closed to new replies.

About this Topic