从循环中获取永久链接以在循环外部使用

时间:2014-03-16 12:51:08

标签: javascript wordpress

在存档页面中,我有一个X帖子列表,每个帖子都有一个缩略图,显示在灯箱幻灯片中。

我正在尝试的是,获取循环中每个帖子项的永久链接,并将其打印在循环外的脚本函数中。

这是存档页面的循环。

<?php 
if ( get_query_var('paged') ) $paged = get_query_var('paged'); 
if ( get_query_var('page') ) $paged = get_query_var('page');
$query = new WP_Query( array( 'post_type' => 'gallery', 'paged' => $paged, 'orderby' => 'rand' ) );

if ( $query->have_posts() ) : ?>

<div class="work-info">
  <a rel="<?php the_permalink();?>" href="<?php echo $imageF[0]; ?>" class="lightbox" data-title="<?php the_title();?>" ></a>
</div>


<?php endwhile; wp_reset_postdata(); ?>
<?php endif; ?>

并在同一个php文件上,就在循环之外......

<script>
jQuery(document).ready(function($){

$('.lightbox').iLightBox(

  {
    skin: 'smooth',
    path: 'horizontal',
    linkId: 'showcase',

social: {
  buttons: {
    facebook: {
      URL: "<?php echo get_permalink();?>",
      text: "Share it on your Timeline"
    },
  }
},

  }
);

}); 
</script>      

如您所见,网址:&#34;&#34; 只会在帖子列表中显示1个随机永久链接,因为它位于循环之外。

我想要的是拥有一个网址:&#34; &#34;每个帖子都有自己的固定链接。

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

<强>更新

在看了插件的代码后,我建议尝试不同的方法。这应该适用于图像库。

您可以使用data-options属性设置每个.lightbox项的共享网址。

试试这个:

<a rel="<?php the_permalink();?>" href="<?php echo $imageF[0]; ?>" class="lightbox" data-title="<?php the_title();?>" data-options="social: { facebook: { URL: '<?php the_permalink(); ?>', text:'Share this photo on Facebook' }, twitter: { URL: '<?php the_permalink(); ?>', text:'Share this photo on Twitter' }   }" ></a>

您的javascript代码应为:

<script>
jQuery(document).ready(function($){

    $('.lightbox').iLightBox({
        skin: 'smooth',
        path: 'horizontal',
        linkId: 'showcase'
    });

}); 
</script> 

正如我从您的代码中看到的,每个.lightbox元素都有一个rel属性,其中包含永久链接。因此,我建议使用类.lightbox(使用jQuery .each()方法)遍历每个元素,并为每个元素添加iLightBox函数。请尝试以下代码:

jQuery(document).ready(function($){

    $('.lightbox').each(function() {

        $(this).iLightBox({
            skin: 'smooth',
            path: 'horizontal',
            linkId: 'showcase',
            social: {
                buttons: {
                    facebook: {
                          URL: $(this).attr("rel"),
                          text: "Share it on your Timeline"
                    }
                }
             }

        });

    });

 });

让我知道它是否有效。

有关jQuery .each()方法here的更多信息。

答案 1 :(得分:0)

不太确定你要对你的脚本做什么,但是要做的就是在循环运行时构建一个永久链接数组

在你的循环开始之前做一个

$permalink_array = array();

然后在每个帖子的链接中

$permalink_array[] = get_the_permalink();

如果要打印所有永久链接,请使用

之类的内容
foreach( $permalink_array as $permalink ) {
    echo $permalink;
}