Site icon DsgnWrks

Helper function to check post meta for existence of search string

Today, I needed to find a way to search through the Carrington Build modules for the existence of a shortcode. Personally I needed this so that I could conditionally load some CSS in the head, but you’re reasons may vary. Hope you find it helpful.

/**
 * Check post meta for existence of search string
 */
function check_wp_meta_for_string( $meta_key, $search, $post_id = null ) {

   if ( ! $post_id ) {
      global $post;

      if ( ! isset( $post->ID ) )
         return false;
      
      $post_id = $post->ID;
   }


   // Get serialized meta
   $meta = get_post_meta( $post_id );

   if ( ! isset( $meta[ $meta_key ][0] ) )
      return false;

   return ( false !== strpos( $meta[ $meta_key ][0], $search ) );
}

// Example usage.. Checking if Carrington build modules contains a shortcode
check_wp_meta_for_string( '_cfct_build_data', '[my-shortcode' );
Exit mobile version