• Resolved WPChina

    (@wordpresschina)


    I want to prepend content to my posts in the Single Posts and RSS Feeds. Here is the code I currently use and it works well:

    add_filter('the_content','add_postdata_to_content');
    function add_postdata_to_content($content) {
    global $post;
    if ( is_single() || is_feed() ) {
      $postdata .= '<!-- BEGIN --><strong>' . get_post_meta( $post->ID, 'cityname', true ) . ', ' . get_the_time('Y-m-d') . '<!-- END --> ';
    return preg_replace('/<p>/', '<p>' . $postdata, $content, 1);
    }
    else 
    {
      $postdata .= '<p>';
    return preg_replace('/<p>/', '<p>' . $postdata, $content, 1);
    }
    }

    But one of my Categories (ID = 409) does not have post meta for the ‘cityname’ field, so I want to always use “New York” in that space.

    What is the best way to include “New York” if the get_post_meta for ‘cityname’ is empty or if it is in the category # 409? it would be best to only fix it for showing “New York” for category 409, but showing it when post meta is empty si also a possibility.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Check if the post meta is an empty string…

    
    add_filter('the_content','add_postdata_to_content');
    function add_postdata_to_content($content) {
        global $post;
        if ( is_single() || is_feed() ) {
    
          $postdata .= '<!-- BEGIN --><strong>';
          // ternary to check if there is post meta value for cityname. if not, use 'New York'
          $postdata .= ( get_post_meta( $post->ID, 'cityname', true ) !== '' ) ? get_post_meta( $post->ID, 'cityname', true ) : 'New York';
          $postdata .= ', ' . get_the_time('Y-m-d') . '<!-- END --> ';
    
          return preg_replace('/<p>/', '<p>' . $postdata, $content, 1);
        } else {
          $postdata .= '<p>';
            return preg_replace('/<p>/', '<p>' . $postdata, $content, 1);
        }
    }
    
    • This reply was modified 6 years, 11 months ago by justinwhall.
    Thread Starter WPChina

    (@wordpresschina)

    Works excellent! Thanks so much~

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Problem with Conditionals in functions.php’ is closed to new replies.