Search code examples
wordpressfacebook-instant-articles

Instant Articles for WP (Wordpress plugin) Selectively discard posts from feed


I'm trying to automatically exclude all articles that don't have a custom field set. I have checked the 'instant_articles_before_render_post' and 'instant_articles_after_render_post' hooks but I wonder how I could use them to prevent the render of the article. Any ideas?


Solution

  • instant_articles_before_render_post and instant_articles_after_render_post are used to launch actions before / after the post rendering but cannot prevent the post to render. What you need to do is to hook on pre_get_posts in order to change the main query used by Facebook Instant Articles.

    If you look in the facebook-instant-articles.php plugin file, you will see the following function:

    function instant_articles_query( $query ) {
        if ( $query->is_main_query() && $query->is_feed( INSTANT_ARTICLES_SLUG ) ) {
            $query->set( 'orderby', 'modified' );
            $query->set( 'posts_per_page', 100 );
            $query->set( 'posts_per_rss', 100 );
            /**
             * If the constant INSTANT_ARTICLES_LIMIT_POSTS is set to true, we will limit the feed
             * to only include posts which are modified within the last 24 hours.
             * Facebook will initially need 100 posts to pass the review, but will only update
             * already imported articles if they are modified within the last 24 hours.
             */
            if ( defined( 'INSTANT_ARTICLES_LIMIT_POSTS' ) && INSTANT_ARTICLES_LIMIT_POSTS ) {
                $query->set( 'date_query', array(
                    array(
                        'column' => 'post_modified',
                        'after'  => '1 day ago',
                    ),
                ) );
            }
        }
    }
    add_action( 'pre_get_posts', 'instant_articles_query', 10, 1 );
    

    You can hook right after this and add your own meta condition like this:

    function instant_articles_query_modified($query) {
        if($query->is_main_query() && isset(INSTANT_ARTICLES_SLUG) && $query->is_feed(INSTANT_ARTICLES_SLUG)) {
            $query->set('meta_query', array(
                array(
                      'key' => 'your_required_meta'
                )
            ));
    }
    add_action('pre_get_posts', 'instant_articles_query_modified', 10, 2);