如果与标签(子弹/名称)匹配,如何获取附件URL(wordpress)

时间:2018-12-03 12:38:10

标签: php wordpress image

如果图像文件名的文件名中包含该标签(单词),我想在标签下显示我的所有附件(图像)。

我的意思是如果我有标签http://example.com/tag/john 我想显示名称中带有 john 的所有图像。
/wp-content/uploads/2018/08/my_name-john.jpg, /wp-content/uploads/2017/06/john_meet-us.jpg,

我是php和wordpress的新手,我不知道是否有可能从浏览器中打开的url中获取标签,然后为该标签查找图像。 我知道它的帮助形式,我还必须提供我尝试使用的代码,然后人们可以帮助我们。但是正如我说的是新的,我用谷歌搜索,尝试使用此代码,但有很多限制,也不知道如何修改以供使用。

<?php  
                function get_attachment_url_by_title( $title ) {

$attachment = get_page_by_title($title, OBJECT, 'attachment');
//print_r($attachment);

  if ( $attachment ){

    $attachment_url = $attachment->guid;

  }else{
    return 'image-not-found';
  }

  return $attachment_url;
}

echo get_attachment_url_by_title('title of image');

                ?>  

上面的代码显示图像,如果我们手动提供图像的标题,其名称必须与文件名相同,则以上代码可以正常工作。所以希望你能回答我的问题。提前致谢。 (对不起,我的英语不好)

1 个答案:

答案 0 :(得分:0)

You can get the attachments url by tag by below Sql Query :

Paste the below code in your current active theme functions.php file.

function get_url_from_tag_name($tag = 'old'){

    global $wpdb;

    $query      =   'SELECT guid FROM `'.$wpdb->prefix.'posts` WHERE guid like "%'.$tag.'%" AND post_type="attachment"';
    $results    =   $wpdb->get_results( $query, OBJECT );

    return $results;
}

I hope it help you. Thanks :)