【问题标题】:Thumbnail and Conditional Links for 2 loops within single.phpsingle.php 中 2 个循环的缩略图和条件链接
【发布时间】:2014-09-13 04:49:03
【问题描述】:

这是我的问题。我希望所有缩略图都链接到帖子
除了 single.php 中的主循环缩略图链接到外部网站
但也为 single.php 中的第二个循环“相关帖子缩略图”链接到帖子

下面的“代码 A”仅实现前 2 个目标。 如何在 single.php“相关帖子缩略图”中创建第二个循环以链接到帖子(而不是外部网站)?

我正在使用:

the_post_thumbnail('large') for main loop in single.php
the_post_thumbnail('thumbnail') for second loop in single.php
the_post_thumbnail('medium') for everything else  

.
“代码 A”:所有缩略图链接到帖子,除了 single.php 中的缩略图链接到外部网站

function my_post_image_html( $html, $post_id, $post_image_id ) { 
if ( is_single() ) { 
    $name = get_post_meta($post_id, 'externalurl', true);
    if( $name ) {           
        $html = '<a href="'.$name.'" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
    }
    return $html;
}
else 
{
    $html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
    return $html;
}
}

add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );

“代码 B”:single.php 中的第二个循环“相关帖子缩略图”

<?php 
$args = array(
    'posts_per_page' => 6,
    'orderby' => rand
);
$the_query = new WP_Query( $args ); 
?>

<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php the_post_thumbnail('thumbnail'); ?></a>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php endwhile;?>

<?php wp_reset_postdata(); ?> 

【问题讨论】:

    标签: php thumbnails conditional-statements wordpress


    【解决方案1】:

    在第二次通过时,您的代码在我的系统上运行良好。固定链接是正确的。但是,您的第二个循环中有一个额外的“)”:

    <?php the_post_thumbnail('thumbnail') ); ?>
    

    尝试删除它,看看情况是否有所改善。

    编辑:

    添加第四个参数:

    function my_post_image_html( $html, $post_id, $post_image_id, $size ) { 
        if ( $size == 'large' ) {
            echo 'large';
        }
    }
    
    add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 4 );
    

    另外,在您的第二个 lop 中,将您要求的尺寸从缩略图更改为大:

     <?php the_post_thumbnail('large'); ?>
    

    【讨论】:

    • 删除多余的“)”时没有变化。目前,该代码将主循环和第二循环(在 single.php 内)中的缩略图链接到外部网站。有没有办法让第二个循环链接到帖子?或者,有没有办法让 the_post_thumbnail('large') 链接到外部网站,而其他缩略图尺寸链接到帖子?
    • 您可以通过在过滤器中添加第四个参数来检查请求的大小,检查编辑。
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 2015-05-24
    • 2017-06-13
    • 2011-10-20
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多