Is there a way to skip compiling all projects during artifactoryPublish while using onlyIf

I have a custom task which on being called with artifactoryPublish should only publish projects with a certain characteristic. In my case, all projects ending with “api”.
On running the command ,
./gradlew publishAllApis artifactoryPublish

I see that only the projects ending with api get deployed to the artifactory but the classes, jar are getting compiled for all projects and not only the ones with “api”.

On running plain ./gradlew project-name:artifactoryPublish, classes and jar get compiled for that specific project and the dependent ones . Is there a way to simulate this behavior in the below script. [compile only api projects]

task publishAllApis () {
    doFirst {
        artifactoryPublish.onlyIf {
           project.name.endsWith("api")
      }
    }
}

The same logic will apply to the install task.

task installAllApis(){
    doLast {
        install.onlyIf {
            apiProject()
        }
    }
}

fyi : The above task is under subprojects which has apply plugin : ‘java’