WordPress.org

Ready to get started?Download WordPress

Forums

use limit words with IF statement (3 posts)

  1. devoninternational
    Member
    Posted 2 years ago #

    I want to use an if statement with the limit word function:

    Limit Word function code:

    function string_limit_words($string, $word_limit) {
      $words = explode(' ', $string, ($word_limit + 1));
      if(count($words) > $word_limit)
      array_pop($words);
      return implode(' ', $words);
    }

    If statement I want to use:

    if ( get_post_type() == "page" && string_limit_words < 14  ) {?>
    			<a> " title="<?php the_title(); ?>"><img src="<?php echo get_stylesheet_directory_uri() ?>/images/page-icn.png" class="blog-icn" title="Read More" width="32" height="32"/><h2 class="blog-title"><?php the_title();?></h2></a>
    		<?php }

    PROBLEM IS:
    This does not work within an if statement "string_limit_words < 14"

    The point of all of this is to limit the post title text in search and blog pages.

    Does the word limit function have something to call like the character limit function does: (strlen($post->post_title) > 57 )

  2. Nikki Blight
    Member
    Posted 2 years ago #

    It doesn't work because 1) you're not calling the function correctly, and 2) the function doesn't return a value for comparison to begin with.

    The function returns a string of words trimmed down to a specified length. You give it some text and a word limit, and it gives you the same text back, but with the extra words trimmed off the end. It would be used to display text, similar to using the_excerpt() or the_content().

    You would use it like this:

    echo string_limit_function('Some text here', 2);

    That would display "Some text".

    If all you're looking to do is limit the length of the title, you would simple use something like:

    echo string_limit_words($post->post_title, 14);

    rather than using the the_title() function.

    If you're wanting to limit the display to ONLY titles that are less than 14 words, you would need to actually count the words in the title, which you could do with a custom function:

    function string_count_words($string) {
      $words = explode(' ', $string);
      return count($words);
    }

    You could then use *that* function in your if statement:

    if ( get_post_type() == "page" && string_count_words($post->post_title) < 14 )

    On a side note, strlen() is not a character limit function. It simply returns the length of a given string, which can then be used for comparison purposes.

  3. devoninternational
    Member
    Posted 2 years ago #

    Fantastic I will soak this all in and reply, much appreciated.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.