需要在最后列出的类别之前添加文本,然后在它的末尾.(Wordpress类别php)


Need to add text before the last listed category and then at the end of it. (Wordpress category php)

我遇到了一个障碍,我希望在我的php代码中实现的设置。这段代码提取清单分组所在的类别,并在屏幕上显示为:

家庭烹饪, 新鲜水果, 晚餐, 快餐

我希望实现的是:

家庭烹饪新鲜水果晚餐速食精选中有特色

如果你注意的话,在单词Quick Meals之前的以及在它之后的Collections是我需要做的更改。我刚刚开始学习php,我不能在不破坏它的情况下进行这种调整。下面是我正在处理的:

如果你能把我从这个问题中拯救出来,我将非常感谢。我想没什么太难的。
$permalink = get_permalink( $id );

$seo = get_the_title()."- offers: ";

$Category_links = ' Featured in ';

$term_list_category = wp_get_post_terms(get_the_ID(), 'listings_categories', array("fields" => "ids"));

$i = 0;

$count = count($term_list_category);
if ( $count > 0 ){
    foreach ( $term_list_category as $term_category ) {
        $thisCat = get_term_by( 'id', $term_category, 'listings_categories');
        $url = '<a class="listing-links" href="/listings/'.$thisCat->{'slug'}.'/'.'" title="'.$thisCat->{'name'}.' - Food listings " >'.$thisCat->{'name'}.'</a>';
        $i ++;
        $seo .= " " . $thisCat->{'name'} . "";
        $Category_links .= " " . $url . "";
        if ($count > 1 && $count !== $i) {$Category_links .= ", ";  $seo .= ", "; }
    }
}

本行下面--> $Category_links .= " "。$ url。

";

将代码改为…

        if($count-1 == $i){
            $Category_links .= " and ";  $seo .= ", ";
        }elseif($count > 1 && $count !== $i){
            $Category_links .= ", ";  $seo .= ", "; 
        }
    }
    $Category_links .= " Collections";      
}

基本上你是在检查你是否在数组($count-1)的最后一个元素的旁边,并插入一个" and "而不是",

然后在循环外添加$Category_links .= " Collections";添加到输出的末尾

我更喜欢字符串输出的简单数组操作;

基本

//example of assigning those categories
$cats = array('Cat 1', 'Cat 2', 'Cat 3', 'Cat 4');
$ccats = count($cats);
foreach($cats as $i => $cat)
{
    //apply slug as needed here     
    $cats[$i] = '<a href="">' . $cat . '</a>';  
    if($i < ($ccats-1))
    {
        $cats[$i] .= ',';
    }
}
array_splice($cats, ($ccats-1), 0, array('and'));
$cats[] = ' Collections';
echo implode($cats, ' ');

实现(未测试)

$cats = wp_get_post_terms(get_the_ID(), 'listings_categories', array("fields" => "ids"));
$ccats = count($cats);
$vcats = array();
foreach($cats as $i => $cat)
{
    //apply slug & name as needed here  
    $vcats[$i] = '<a class="listing-links" href="/listing/' . $cat->slug . '" title="' . $cat->name . '">' . $cat->name . '</a>';
    if($i < ($ccats-1))
    {
        $vcats[$i] .= ',';
    }
}
array_splice($vcats, ($ccats-1), 0, array('and'));
echo 'Featured in ' . implode($vcats, ' ') . ' Collections';

希望能有所帮助

相关文章: