Mr.Json
Mr.Json

Reputation: 149

wp_get_attachment_url generates different links

I write this code for get all attachments of a post:

$args = array(
    'order'          => 'ASC',
    'post_type'      => 'attachment',
    'post_parent'    => $pid,
    'exclude'    => $exclude,
    'numberposts'    => -1,
    'post_status'    => null,
);
$attachments = get_posts($args);


foreach($attachments as $at)
{
    ?>
    <li> <a href="<?php echo wp_get_attachment_url($at->ID); ?>"><?php echo $at->post_title; ?></a>
    </li>
<?php } ?>

For .zip or .xlsx file types it generate a url like this:

http://localhost/mywp/wp-contents/uploads/test.zip (it's ok)

But for .docx file types it generate a url like this:

http://localhost/mywp/?attachment_id=710 (This link not work (download) for me.)

What is problem?

Upvotes: 0

Views: 337

Answers (2)

Mr.Json
Mr.Json

Reputation: 149

My problem is in Ajax upload!! wp_handle_upload have error. (mime type error) and wp_insert_attachment insert empty record. and cause to create wrong link. Thanks.

Upvotes: 1

Sudharshan Nair
Sudharshan Nair

Reputation: 1267

Have you tried get_attachment_link() ? Here is the sample code

$attachment_id = 1; // ID of attachment
$attachment_page = get_attachment_link( $attachment_id ); 
?>
<a href="<?php echo $attachment_page; ?>"><?php echo get_the_title( $attachment_id ); ?></a>

Upvotes: 0

Related Questions