从术语创建自定义链接

时间:2013-01-15 09:39:42

标签: php wordpress

我正在为Wordpress术语创建自定义链接,我已完成以下操作:

<?php $terms = get_the_terms( $post->ID, 'blog' );                  
if ( $terms && ! is_wp_error( $terms ) ) : 
    $blog_links = array();
    $blog_slugs = array();

    foreach ( $terms as $term ) {
        $blog_links[] = $term->name;
    }

    foreach ( $terms as $termslug ) {
        $blog_slugs[] = $termslug->slug;
    }   

    $blog = join( ", ", $blog_links );
    $blogs = join( ", ", $blog_slugs ); 
?>

<a href="<?php bloginfo('url'); ?>/blog/<?php echo $blogs; ?>"><?php echo $blog; ?></a>
<?php endif; ?>

这会创建网址:

http://www.domain.com/blog/news,%20guest-blogs

链接的文字看起来像这样(即它是一个链接 - 见截图):

enter image description here

哪个很近!我实际上想要将每个术语分成一个链接(中间有一个逗号)并制作网址http://www.domain.com/blog/newshttp://www.domain.com/blog/guest-blogs。我想我错过了一个foreach来分别输出每个链接。

有人可以帮我把最后一点纠正吗?

2 个答案:

答案 0 :(得分:1)

可能很容易使用

<?php echo get_the_term_list( $post->ID, 'blog', '', ', ', '' ); ?>


你的代码有问题......也许这样的事情会......

<?php $terms = get_the_terms( $post->ID, 'blog' );                  
if ( $terms && ! is_wp_error( $terms ) ) : 
    $blogs = array();

    foreach ( $terms as $term ) {
        $blogs[] = '<a href="' . get_bloginfo('url') . '/blog/'. $term->slug .'">' . $term->name . '</a>';
    }    

    $blog_links = join( ", ", $blogs);

    echo $blog_links;

endif; ?>

答案 1 :(得分:0)

您的代码只提供一个输出a元素,您需要修改此代码段,以便$terms中的每个元素生成一个具有正确href和锚点的a元素。这可能是一个解决方案

<?php 
$terms = get_the_terms( $post->ID, 'blog' );                  
if ( $terms && ! is_wp_error( $terms ) ) : 
    $output = array();
    foreach($terms as $term):
        // Use sprintf to quickly modify the template
        $output[] = sprintf("<a href='%s'>%s</a>", get_bloginfo('url') . '/blog/' . $term->slug, $term->name);
    endforeach;
    echo implode(', ' $output); // This is the result
endif; 
?>
相关问题