سؤال

I am currently using this code to display the final child in a hierarchical taxonomy. For example, a post tagged 20th Century > 1990s > 1994 should ultimately only show 1994.

The code below works for most Parent/Child groups except for ones that end with 0s and have a child of 0. For example, 20th Century > 1990s > 1990 outputs 1990s (and not 1990).

I think the problem is that array() is using an alphanumerical method that outputs 20xxxx, 1990, 1990x. Thus thinking the final child is 1990s (not 1990).

Is there a way to ignore letters in an array? Or is there a better order to use than array()?

  <?php

    $terms = get_the_terms( $post->ID, 'From' );

        if ( !empty( $terms ) ) {
            $output = array();
            foreach ( $terms as $term ){
                if( 0 != $term->parent )
                    $output[] = '<a href="' . get_term_link( $term ) .'">' . $term->name . '</a>';
            }

                if( count( $output ) )
                echo '<p><b>' . __('','From') . '</b> ' . end($output) . '</p>';
            }
    ?>

If you need, you can also preview my site here: dev.jamesoclaire.com The first post shows "2010s" when instead it should show "2010"

هل كانت مفيدة؟

المحلول 2

A friend helped me realize I was unfortunately asking the wrong question. What I needed to do was choose the correct term when I ran get_the_terms. Since I wanted to display the year only I excluded any $term->name which were not 4 characters long.

<?php
        $terms = get_the_terms( $post->ID, 'From' );
if ( !empty( $terms ) ) {
    foreach ( $terms as $term ){
        if( ( 0 != $term->parent ) and ( strlen($term->name) == 4 ) )
            $output = '<a href="' . get_term_link( $term ) .'">' . $term->name . '</a>';
    }

    if ( !empty( $output ) )
        echo '<p><b>' . __('','From') . '</b> ' . $output . '</p>';
}
?>

نصائح أخرى

You can use explode to explode each item separated by a > to put them into an array. Then you can use array_pop to get the last item of the array.

http://us3.php.net/array_pop

Finally, if necessary, you can filter out the characters that you do not wish to have in your string.

$string = '20th Century > 1990s > 1994';

// EXPLODE THE ITEMS AT THE GREATER THAN SIGN    
$timeline_items = explode('>', $string);

// POP THE LAST ITEM OFF OF THE ARRAY AND STORE IT IN A VARIABLE
$last_item = trim(array_pop($timeline_items));

To answer your question directly, you can strip out any non-numeric characters by using Regular Expressions.

$string = preg_replace('/[^0-9 >]/i', '', $string);

But that may not give you exactly what you are looking for. For example:

$string = '20th Century > 1990s > 1994';
$string = preg_replace('/[^0-9 >]/i', '', $string);
print $string;

Will give you:

20 > 1990 > 1994
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top