Bulk or Mass knowledge article archive in Apex

In Salesforce, we can’t directly change the knowledge article PublishStatus using the apex

salesforce provides some inbuild class methods to handle the logic, the link is given below

KbManagement Namespace

Here we have one real-time scenario.

Task: Get all the published knowledge records and archive everything with the help of apex.

We know we cant direct update the publishstatus filed value because it’s not an editable field. In this batch class, In execute section we used PublishService method in the parameters we are passing knowlegearticleid. The second parameter for archive schedule if we are giving any date. the record will be archived on given data but here we passed a null value so the record will be archived immediately.

Here we are building email in the apex class itself. we are sending email notifications to the record owner.

global class articleArchiveBatch implements Schedulable, Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC){  
        return Database.getQueryLocator([SELECT id,PublishStatus,,OwnerId,CreatedBy.Email from Knowledge__kav WHERE PublishStatus = 'online']);
    global void execute(Database.BatchableContext BC,  List<Knowledge__kav> knowledgeList) {

        List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();

        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = ''];
        for(Knowledge__kav kv : knowledgeList){

            List<String> toAddresses = new List<String>();          
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            KbManagement.PublishingService.archiveOnlineArticle(kv.KnowledgeArticleId, null);

            if ( owea.size() > 0 ) {
            mail.setSubject('Notification for Creator');
            String messageBody = '<html><body>Hi ' + +',<br><br>This message is to notify you that KB article which you are the author, its archived now .</body></html>';

    global void finish(Database.BatchableContext BC) {
    global void execute(SchedulableContext SC) {
        articleArchiveBatch batch = new articleArchiveBatch();
        Database.executeBatch(batch, 200);     	

You can schedule the batch class or run immediately based on your business need 🙂

Leave A Comment