Microsoft SharePoint WordPress integration - createIT

Get a free advice now!

    Pick the topic

    Developer OutsourcingWeb developingApp developingDigital MarketingeCommerce systemseEntertainment systems

    Thank you for your message. It has been sent.


    Microsoft SharePoint WordPress integration

    Microsoft SharePoint WordPress integration

    CHALLENGE: Fetch the documents list from SharePoint Office 365

    SOLUTION: Create a WordPress plugin that will save items as custom post type

    Microsoft SharePoint WordPress integration

    SharePoint Online is a collaborative platform and a document management system. It’s hosted in the cloud (Microsoft office365 subscription). All documents are stored in SharePoint, we would like to fetch them and display in WordPress website. We are going to create WordPress plugin integration that will synchronize the data from sharepoint.

    Microsoft SharePoint REST API access

    We need to: configure app permissions to ‘share MyDocuments Library List’ and set up Client Id and Client Secret.

    The first step will be to create a new app:

    Then, we will set up proper permissions using the url: – to do a lookup, you have to remember the client ID (also known as the add-in ID) that was used to register the add-in. To set up , read only rights – this code should be pasted into the settings text area:

    <AppPermissionRequests AllowAppOnlyPolicy=”true”>

    <AppPermissionRequest Scope=”http://sharepoint/content/sitecollection/web/list”

    Right=”Read” />


    The last step – to verify that app was created – go to:

    WordPress sharepoint integration

    We’ve created a simple plugin that connects to the Sharepoint REST API and saves items as custom post type items. In addition – all meta data is saved as WordPress meta fields and media files are saved into the wp-content subdirectory.

    We’re using PHP Library for Office 365 that will make it possible to connect to REST API and conduct one-way sync of files / data.

    // Office 365 Library for PHP. A REST/OData based client library for Office 365.
    require_once __DIR__ . '/../vendor/autoload.php';
    use Office365\Runtime\Auth\ClientCredential;
    use Office365\SharePoint\ClientContext;
    private function ct_connect_to_api(){
        $clientId = CT_CLIENT_ID;
        $clientSecret = CT_CLIENT_SECRET;
        $tenant_prefix = 'abc123';
        $subsite = 'sites/Site1';
        $listTitle = 'MyDocuments Library';
        $config = array(
            'TenantName' => "{$tenant_prefix}",
            'Url' => "https://{$tenant_prefix}".$subsite,
            'OneDriveUrl' => "https://{$tenant_prefix}",
            'AdminTenantUrl' => "https://{$tenant_prefix}",
            'Password' => 'aaa',
            'UserName' => 'bbb',
            'ClientId' => $clientId,
            'ClientSecret' => $clientSecret,
            'RedirectUrl' => "https://{$tenant_prefix}",
            'TestAccountName' => "jdoe2@{$tenant_prefix}",
            'TestAltAccountName' => "wellis2@{$tenant_prefix}",
            'listTitle' => $listTitle
        try {
            $credentials = new ClientCredential($config['ClientId'], $config['ClientSecret']);
            $this->ctx = (new ClientContext($config['Url']))->withCredentials($credentials);
            $list = $this->ctx->getWeb()->getLists()->getByTitle($config['listTitle']);
            $items = $list->getItems();
            $this->ctx->load($items, array('FileRef','FileDirRef','EncodedAbsUrl','*'));
        catch (Exception $e) {
            echo 'Authentication failed: ',  $e->getMessage(), "\n";

    Now, we’re passing data to WordPress – and adding elements into the database. We’re creating the uploads/mydocuments directory and will store all files there.

    private function ct_push_to_WordPress($items){
        $counter = 0;
        foreach ($items as $index => $item){
            $sourceFileUrl = $item->getProperty('FileRef');
            $filename =  basename($sourceFileUrl);
            $ext  = (new SplFileInfo($sourceFileUrl))->getExtension();
            $targetWpFileName = urlencode(md5( $sourceFileUrl ) ). "." .$ext;
            $introTxt = $item->getProperty('IntroTxt');
            $post_title = sanitize_title( $filename );
            $new_post = array(
                'post_title' => $post_title,
                'post_status' => 'publish',
                'post_type' => 'mydocs',
                'post_content' => $introTxt
            global $wpdb;
            $query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_name = %s', $post_title);
            $postExists = $wpdb->get_var( $query );
            // Add new - or update existing
                $post_id = wp_insert_post( $new_post );
            } else {
                $post_id = $postExists;
            update_field( 'filename', $filename, $post_id );
            update_field( 'sharepoint_index', $index, $post_id );
            $sharepoint_fields = Wp_Sync()->get_all_sp_props();
            foreach($sharepoint_fields as $prop){
                $cf_name = Wp_Sync()->ct_get_cf_name($prop);
                update_field(  $cf_name, $item->getProperty($prop), $post_id );
            $upload_dir = wp_upload_dir();
            $dir = trailingslashit( $upload_dir['basedir'] )  . 'mydocuments/'; // Set storage directory path
            $fileContent = Office365\SharePoint\File::openBinary($this->ctx, $sourceFileUrl);
            if (!file_exists($dir)) {
                mkdir($dir, 0755, true);
            if(file_exists ($dir . $targetWpFileName)){
                update_field( 'filepath','/wp-content/uploads/mydocuments/' . $targetWpFileName, $post_id );
            $my_post = [
                'ID'           => $post_id,
                'post_content' => $introTxt
            wp_update_post( $my_post );
        return $counter;

    Custom fields’ (sharepoint columns) names – should be defined in get_all_sp_props() :

    public function get_all_sp_props(){
        return array(

    Helper function – defines WordPress custom fields naming convention:

    public function ct_get_cf_name($prop){
        $cf_prefix = 'myprefix123';
        $cf_name = $cf_prefix . strtolower($prop);
        return $cf_name;


    That’s it. This basic integration makes it possible to fetch items from Sharepoint to WordPress. We can extend it later by: adding taxonomy terms instead of custom fields, creating shortcode for displaying items and adding the filtering option. We might also want to control the visibility of the items (use prop value to restrict some items only for logged-in WordPress users).

    0 response

    Add comment

    Your email address will not be published. Required fields are marked *

    Popular news

    How to Get and Use the ChatGPT API
    • Dev Tips and Tricks

    How to Get and Use the ChatGPT API

    April 25, 2024 by createIT
    eCommerce growth – is your business ready?
    • Services
    • Trends

    eCommerce growth – is your business ready?

    April 8, 2024 by createIT
    Digital marketing without third-party cookies – new rules
    • Technology
    • Trends

    Digital marketing without third-party cookies – new rules

    February 21, 2024 by createIT
    eCommerce healthcheck
    • Services
    • Trends

    eCommerce healthcheck

    January 24, 2024 by createIT
    Live Visitor Count in WooCommerce with SSE
    • Dev Tips and Tricks

    Live Visitor Count in WooCommerce with SSE

    December 12, 2023 by createIT
    Calculate shipping costs programmatically in WooCommerce
    • Dev Tips and Tricks

    Calculate shipping costs programmatically in WooCommerce

    December 11, 2023 by createIT
    Designing a cookie consent modal certified by TCF IAB
    • Dev Tips and Tricks

    Designing a cookie consent modal certified by TCF IAB

    December 7, 2023 by createIT

    Support – Tips and Tricks
    All tips in one place, and the database keeps growing. Stay up to date and optimize your work!

    Contact us