Category: Filter

  • How to execute shortcode in any string or custom field in WordPress

    You can use WordPress filter the_content and apply it to any string or custom field data to display its HTML content as well as render or execute any shortcode in it.

    Here is a code snippet, where a string with some HTML content and a shortcode in it.

    // $data is defined as a string with HTML code as well as WordPress shortcode in it
    $data = '<div class="custom-html-code"> <h2> Here is a list of Recent Posts</h2> [recent-posts posts="5"]</div>';
    echo apply_filters( 'the_content', $data); 
    

    The above code will not just display the HTML code, But also when it encounters the [recent-posts] shortcode, it will execute it. It will also apply any other filter that has been applied to the_content filter.

    Now let’s say, you have a custom Textarea field that you created using ACF ( advanced custom fields plugin) in your custom post, and it has HTML data as well as shortcodes. In that case, you can use code as shown in the example below.

    // CODE FOR ACF CUSTOM FIELD
    echo apply_filters( 'the_content', get_field("field_name_here") ); 
    
    // CODE FOR Other custom field using post meta data function
    echo apply_filters( 'the_content', get_post_meta($post->ID,"field_name_here",true) ); 
    

  • How to make Gutenberg block editor work, when WordPress Address & Site Address are different domains

    Recently, I worked on a project where the WordPress site needed to have one domain for Site Address(SITE URL) and another one for WordPress Address(HOME URL). Everything was working fine. Except, whenever we tried to publish a post in Gutenberg editor, we were getting an error saying “Updating failed. “. This is also the case when you are using WordPress as headless CMS.

    Soon, I realized that as we were accessing the site admin section from the Site Address, and when we were hitting the update or publish button on Gutenberg editor, it was sending a request to the REST API with WordPress Address(HOME URL) as it’s base URL. The REST API URL should be the same domain from which the request is being sent. So, we just have to make WordPress Gutenberg editor use the Site Address (SITE URL) instead of WordPress Address(HOME URL) as a base for API.

    Here is the snippet code is given below, which uses ‘rest_url‘ filter to replace the HOME URL in REST API URL to SITE URL.

    // change WordPress API URL to HOME URL
    add_filter('rest_url', 'wptips_home_url_as_api_url');
    function wptips_home_url_as_api_url($url) {
        $url = str_replace(home_url(),site_url() , $url);
        return $url;
    }

    Please let me know in the comment section below if you ever had to work on a project where you had to assign different domains to Site Address and WordPress Address.