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

    June 10, 2022
    Last update: September 4, 2024
    3 min read
    32
    0
    0
    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: https://abc123.sharepoint.com/sites/Site1/_layouts/15/AppRegNew.aspx

    Then, we will set up proper permissions using the url: https://abc123.sharepoint.com/sites/Site1/_layouts/15/AppPrincipals.aspx – 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” />

    </AppPermissionRequests>

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

    https://abc123.sharepoint.com/sites/Site1/_layouts/15/AppPrincipals.aspx

    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.
    // https://github.com/vgrem/phpSPO
    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}.onmicrosoft.com",
            'Url' => "https://{$tenant_prefix}.sharepoint.com/".$subsite,
            'OneDriveUrl' => "https://{$tenant_prefix}-my.sharepoint.com",
            'AdminTenantUrl' => "https://{$tenant_prefix}-admin.sharepoint.com",
            'Password' => 'aaa',
            'UserName' => 'bbb',
            'ClientId' => $clientId,
            'ClientSecret' => $clientSecret,
            'RedirectUrl' => "https://{$tenant_prefix}.sharepoint.com",
            'TestAccountName' => "jdoe2@{$tenant_prefix}.onmicrosoft.com",
            'TestAltAccountName' => "wellis2@{$tenant_prefix}.onmicrosoft.com",
            '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','*'));
            $this->ctx->executeQuery();
            $this->ct_push_to_WordPress($items);
        }
        catch (Exception $e) {
            echo 'Authentication failed: ',  $e->getMessage(), "\n";
        }
        exit;
    }

    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
            if(is_null($postExists)){
                $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);
            }
            file_put_contents($dir.$targetWpFileName,$fileContent);
            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 );
            $counter++;
        }
        return $counter;
    }

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

    public function get_all_sp_props(){
        return array(
            'FileSystemObjectType',
            'Id',
            'ServerRedirectedEmbedUri',
            'ServerRedirectedEmbedUrl',
            'ContentTypeId',
            'ComplianceAssetId',
            'Title',
            'Doc_x002e_Type',
            'Doc_x002e_Nr_x002e_',
            'IntroTxt',
            'Created',
            'AuthorId',
            'GUID'
        );
    }

    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;
    }

    Summary

    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).

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

    Contact us