循环遍历帖子中发布的链接的所有网址(WordPress)

时间:2018-03-30 17:27:35

标签: php wordpress

我有一个循环,可以从自定义帖子类型中获取帖子的内容。这篇特定帖子的内容有一些指向外部图像的链接,我想在灯箱中显示 - 当然是一个接一个:

`

    $args = array(
        post_type => 'xyz',
        'p' => 128

    );

    $custom_loop = new WP_Query($args);
    if ( $custom_loop->have_posts() ) : while ( $custom_loop->have_posts() ) : $custom_loop->the_post(); ?>
    <a href="<?php * what do I have to enter here * ?>">
    <h2><?php the_title();?></h2>
    <img src="def">
    </a>
     <?php endwhile; else : ?>
        <?php get_template_part('template_parts/content','error');?>
    <?php endif; wp_reset_postdata(); ?>`

问题是:我如何遍历帖子中提供的所有链接的所有网址?我只知道这个:wp_get_attachment_url();

但是我不想要附加图像的网址,我只想要帖子中列出的链接的网址。在前端,这些链接提供的图像应该在点击链接后显示在灯箱中,该链接包括帖子标题(h2)和缩略图(img)。这是计划:-)

也许我需要一个循环内部循环只能通过帖子中的链接循环?你知道,我完全迷失了:-感谢任何想法!

2 个答案:

答案 0 :(得分:0)

所有链接是否已经在图片代码中?如果它们已经在图像标记中,则无需浏览链接并重新生成灯箱。您可以执行一些jquery并在这些图像上启用灯箱。如果链接不在图片标签中,我认为您可以执行以下操作:

$args = array(
    post_type => 'xyz',
    'p' => 128

);

//We define the regular expression we will be using to fetch all links from the content;
$pattern = '/<a\s+(?:[^"\'>]+|"[^"]*"|\'[^\']*\')*href="([^"]+)"|\'[^\']+\'|[^<>\s]+/i';

//Start the WP_Query
$custom_loop = new WP_Query($args);
if ( $custom_loop->have_posts() ){
    while ( $custom_loop->have_posts() ){
        $custom_loop->the_post();

        //Perform the regular expression match to get all links from post content
        preg_match_all( $pattern, get_the_content(), $matches );

        //all matches found will be stored in $matches[1]
        if(isset($matches[1]){

            //We make sure to clear all empty values
            $links = array_filter( $matches[1] );

            //Loop through all the links
            foreach ( $links as $link ) {

                //We make sure its a valid url - here we might have '#' since '<a href="#"></a>' will still be fetched by regular expression
                if ( filter_var( $link, FILTER_VALIDATE_URL ) ) {

                    //If links you will be fetching might not be an image link you have to also add a conditional check to make sure the url is an image source

                    //Generate your links for lightbox

                }
            }
        }
    }
}

答案 1 :(得分:0)

@Omar Tani:不幸的是,我无法让这段代码适合我。因此,我为每个url使用了一个元框,然后使用以下代码在代码中调用它:

<?php $... = get_post_custom( $post->ID ); ?>

<a href="<?php echo $...["image1"][0]; ?>">

无论如何,谢谢你的帮助!