intoxstudio / content-aware-sidebars

WordPress Plugin to create and display custom sidebars according to the content being viewed. Fast and powerful.
https://dev.institute/wordpress-sidebars/
GNU General Public License v3.0
24 stars 3 forks source link

Sidebar widget extraction from the plugin #24

Open mde-pach opened 5 months ago

mde-pach commented 5 months ago

Hello there, first of all thanks a lot for your work on this plugin ! I'm currently working on a migration from this plugin to a more custom internal solution and we would like to being able to extract as many configuration of content aware sidebars as possible from each pages.

However, we are not able to understand the code and perform such operation yet.

My question is: How can I identify every sidebar which are assigned to a post (or the list of sidebars assigned to a post) ? (We want to do it programatically, not using an extract feature)

If there is any documentation that I haven't found yet that you think fits my use case, I'd be very happy to have it :)

Thanks for your help !

mde-pach commented 5 months ago

FYI, here is our current implementation:

function get_sidebars_by_post($post_id) {
    global $wpdb;

    $meta_key = '_ca_post_type';
    $query_condition = $wpdb->prepare("
        SELECT post_id
        FROM {$wpdb->postmeta}
        WHERE meta_value = %d
        AND meta_key = %s
        ORDER BY meta_value ASC
    ", $post_id, $meta_key);

    $sidebar_meta_results = $wpdb->get_results($query_condition);

    if (!empty($sidebar_meta_results)) {
        $post_ids = array_map(function($result) {
            return $result->post_id;
        }, $sidebar_meta_results);

        $post_ids_string = implode(',', array_map('intval', $post_ids));

        $sidebar_query = "
            SELECT DISTINCT p.post_parent
            FROM {$wpdb->posts} AS p
            INNER JOIN {$wpdb->posts} AS parent
            ON p.post_parent = parent.ID
            WHERE p.ID IN ($post_ids_string)
            AND parent.post_status = 'publish'
            ORDER BY p.post_parent ASC
        ";

        $sidebar_id_results = $wpdb->get_results($sidebar_query);

        $sidebars = [];

        if (!empty($sidebar_id_results)) {
            foreach ($sidebar_id_results as $result) {
                $sidebar_id = $result->post_parent;
                $sidebar_contents = get_sidebar_contents("ca-sidebar-" . $sidebar_id);
                $sidebars[] = $sidebar_contents;
            }
        }
    }

    return $sidebars;
}