10up / distributor

Share content between your websites.
https://distributorplugin.com
GNU General Public License v2.0
618 stars 156 forks source link

Filter content of pulled posts #1226

Closed IonTulbure closed 1 month ago

IonTulbure commented 1 month ago

Describe your question

Hi. Posts on remote site have shortcodes which insert different html content into post body. How can we filter post_content of pulled posts (both draft and published post with Distributor).

What action or filter to use for this scenario ? Where it is best to implement this, on the source site or the target one ?

I can strip the html tags with preg_replace on save_post hook but it will run for normal post inserts which isn't alright.

Code of Conduct

peterwilsoncc commented 1 month ago

@IonTulbure You can use the dt_pull_post_args filter to modify the content of a post when pulling from one site to another:

<?php

namespace Distributor\Ticket\FilterPulledContent;

/**
 * Modify the content of a post before it is pulled into the local site.
 *
 * @param array $post_args The post arguments passed to `wp_insert_post()` and `wp_update_post()`.
 * @return array The modified post arguments.
 */
function modify_pulled_post_content( $post_args ) {
    // Modify the post content.
    $post_args['post_content'] = 'Modified content';

    return $post_args;
}

add_filter( 'dt_pull_post_args', __NAMESPACE__ . '\\modify_pulled_post_content' );

This code runs on the site that the content is being pulled to, ie the site you visit to access the pull screen.

IonTulbure commented 1 month ago

@peterwilsoncc Hi. It works, much appreciated !

In case someone is interested. I filtered out the shorcode html with preg_replace. It removes all content inside custom tags like <shortcode> </shortcode>.

/**
 * Filter out shortcode content when posts are pulled.
 * 
 */

add_filter('dt_pull_post_args', 'modify_pulled_post_content');

function modify_pulled_post_content($post_args)
{
    // define a function to remove content inside custom HTML tags
    function remove_custom_tags($content)
    {
        // define the custom tags you want to remove content from
        $tags = array('shortcode');

        foreach ($tags as $tag) {
            // regular expression to match and remove content inside the custom tags
            $pattern = "/<\s*$tag\b[^>]*>.*?<\s*\/\s*$tag\s*>/is";
            $content = preg_replace($pattern, '', $content);
        }

        return $content;
    }

    // modify the post content by removing custom tags
    if (isset($post_args['post_content'])) {
        $post_args['post_content'] = remove_custom_tags($post_args['post_content']);
    }

    return $post_args;
}
IonTulbure commented 1 month ago

Issue solved