If you want to add any shortcode for posts on your androapp mobile app than you can do so by adding below code in your themes functions.php
add_filter( 'json_prepare_post','androapp_overwrite_content', 11, 3 ); function androapp_overwrite_content($data, $post_array, $context) { $textToBeAdded = do_shortcode("[related_post_shortcode]"); $data['pwapp_post_content'] = $data['pwapp_post_content'].$textToBeAdded; return $data; }
If you want to use post id or some other information you can use $post and $data objects, see below example to use post id
add_filter( 'json_prepare_post','androapp_overwrite_content', 11, 3 ); function androapp_overwrite_content($data, $post_array, $context) { $pid = $post_array['ID']; $textToBeAdded = do_shortcode("[related_post id=$pid ]"); $data['pwapp_post_content'] = $data['pwapp_post_content'].$textToBeAdded; return $data; }
Few of the shortcodes usage global $post object in that case you can use below code
add_filter( 'json_prepare_post','androapp_overwrite_content', 11, 3 ); function androapp_overwrite_content($data, $post_array, $context) { global $post; $pid = $post_array['ID']; $post = get_post($pid); $textToBeAdded = do_shortcode("[your_shortcode id=$pid ]"); $data['pwapp_post_content'] = $data['pwapp_post_content'].$textToBeAdded; return $data; }
Some of the shortcodes behave differently on homepage than the post page, while fetching posts data from REST calls using WP REST API, shortcode considers it as request from homepage, in that case it does not work as expected.
As a temporary fix for this problem, we can overwrite is_home value like below
add_filter( 'json_prepare_post','androapp_overwrite_content', 11, 3 ); function androapp_overwrite_content($data, $post_array, $context) { global $post; global $wp_query; $wp_query->is_home = false; $pid = $post_array['ID']; $post = get_post($pid); $textToBeAdded = do_shortcode("[your_shortcode id=$pid ]"); $data['pwapp_post_content'] = $data['pwapp_post_content'].$textToBeAdded; return $data; }
Note: in this case, shortcode will work as expected from the second post, first post out of every 10 post will not work properly, we will tell you how to handle that scenario in our next post 🙂