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

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

    Comments
    0 response

    Add comment

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

    Popular news

    Fetching Time records from ActiveCollab API
    • Dev Tips and Tricks

    Fetching Time records from ActiveCollab API

    September 9, 2024 by createIT
    Docker Compose for PrestaShop
    • Dev Tips and Tricks

    Docker Compose for PrestaShop

    September 2, 2024 by createIT
    WordPress wizard in admin – step by step
    • Dev Tips and Tricks

    WordPress wizard in admin – step by step

    August 29, 2024 by createIT
    Order Status Sync between PrestaShop and External APIs
    • Dev Tips and Tricks

    Order Status Sync between PrestaShop and External APIs

    August 26, 2024 by createIT
    What is PHP used for in web development 
    • Dev Tips and Tricks

    What is PHP used for in web development 

    August 22, 2024 by createIT
    Automating WooCommerce product availability date
    • Dev Tips and Tricks

    Automating WooCommerce product availability date

    August 15, 2024 by createIT
    WP Quiz Adventure – FAQ
    • Dev Tips and Tricks

    WP Quiz Adventure – FAQ

    August 12, 2024 by createIT
    Retrieval Augmented Generation tutorial and OpenAI example
    • Dev Tips and Tricks

    Retrieval Augmented Generation tutorial and OpenAI example

    August 8, 2024 by createIT
    10 useful SEO tools for the iGaming industry
    • Services
    • Technology

    10 useful SEO tools for the iGaming industry

    August 5, 2024 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