Why not have Wordpress code transform the post to HTML for you as it already does for your regular site? One of the unfortunate parts of the Wordpress architecture is that it does not cleanly decouple your data from your display concerns (as you are finding out). Since the Wordpress app "owns" translating the posts in the DB into HTML, why would't Wordpress still own this for your mobile view (perhaps vaivia different template (even, even one that just contains HTML fragments for asynchronous delivery to mobile app). This will likely lead to less breakage as changes in your Wordpress site are made, as you would rely on the same view-generation logic.
Now, with regards to your code as is:
- Consider
foreach($post_content_array as $word)instead offor(...)for this main loop. I don't see where you are doing any operations here which require you to refer to the specific index value for the string being evaluated. - It seems odd to me that you would pass in a string to this function, yet return an array. I would think this function should return the reassembled string such that the caller doesn't have to understand the inner workings of the function.
- Consider inverting your conditionals and/or adding
continueto de-nest large sections of your code.
For example:
if(strpos($post_content_array[$x], '[caption') !== false){
$caption_tag_element = true;
continue;
}
if($caption_tag_element === false){
array_push($post_content_filtered, $post_content_array[$x]);
continue;
}
// rest of code, now without nesting
These sorts of "quick exits" can make your code much easier to read and less prone to bugs due to fewer codepaths. There are rarely reasons to have an else condition (like when one of two side-effects need to occur), so try to design them away when possible.
- You should default to using strict logical comparisons as opposed to their loose counterparts. Very seldom in code do you need the flexibility to evaluate a condition in a type-inspecific manner. Try to use exact comparisons by default to make your code less error prone against unexpected truthy/falsey behaviors.
- You have WAY too many comments. Let your code speak for itself.