Microsoft SharePoint WordPress integration

Microsoft SharePoint WordPress integration
TAGS: WordPress

Microsoft SharePoint WordPress integration


Fetch the documents list from SharePoint Office 365
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' => "[email protected]{$tenant_prefix}",
        'TestAltAccountName' => "[email protected]{$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).


Need help?

  • Looking for support from experienced programmers?

  • Need to fix a bug in the code?

  • Want to customize your webste/application?


This is okay, if you are looking to create a document repository. But some (most) people would want this to sync to the media library and use the same folder structures that you are using in Sharepoint.

Would love to see it work with the Media Library instead of CPTs.

Would you be able to publish SharePoint news articles to WordPress. or is this likely better as a pdf type of publication.



Your email address will not be published.

createIT Contact