How to Assign product to specific category Magento 2?

You can add the product to the given categories in Magento 2. You can add a single product to multiple categories with product SKU.

Let’s Product SKU is “24-MB05” and you want to add this product to multiple categories, You need category id to an assigned product. We have to pass the category id as an array in the method defined below.

Using interface, Magento\Catalog\Api\CategoryLinkManagementInterface with assignProductToCategories($productSku, array $categoryIds) method used to add to specific category programmatically.

<?php
namespace Jesadiya\AssignedProduct\Model;

use Exception;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\Data\CategoryProductLinkInterface;

class AssignedProductToCategory
{
    /**
     * @var CategoryLinkManagementInterface
     */
    private $categoryLinkManagement;

    public function __construct(
        CategoryLinkManagementInterface $categoryLinkManagement
    ) {
        $this->categoryLinkManagement = $categoryLinkManagement;
    }

    /**
     * Assigned Product to single/multiple Category
     *
     * @param string $productSku
     * @param int[] $categoryIds
     * @return bool
     */
    public function assignedProductToCategory(string $productSku, array $categoryIds)
    {
        $hasProductAssignedSuccess = false;
        try {
            $hasProductAssignedSuccess = $this->categoryLinkManagement->assignProductToCategories($productSku, $categoryIds);
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage());
        }

        return $hasProductAssignedSuccess;
    }
}

Add Product SKU as $sku value and Pass Category id as array value in $categoryId variable. If you want to assigned products to a single category, add only single category id value otherwise add multiple category id values.

$sku = "24-MB05";
$categoryId = ["6", "7"];
$productAssigned = $this->assignedProductToCategory($sku, $categoryId);

Output:
Boolean