TriTan CMS has different api's for user, post, post type, etc. In this article, I will show you how to create a user programmatically using the user api. Four things need to happen or be present for it to work: array of user data, using the correct function, set the user's role and email the user new login details (optional).

User Data Array

In the user data array, the required fields are user_login, user_email, user_status and user_pass. All other fields are optional.

use TriTan\Functions as func;

$password = func\ttcms_generate_password(12, false);
$data = [
    'user_login' => (string) 'ttcmseditor',
    'user_fname' => (string) 'James',
    'user_lname' => (string) 'Fox',
    'user_email' => (string) 'jfox@ttcmsneweditor.org',
    'user_status' => (string) 'A',
    'user_pass' => (string) $password
];

Insert User Function

We will use the ttcms_insert_user function in order to create our new user with the array data above:

$user_id = func\ttcms_insert_user($data);

Set User's Role

The next thing we need to do is set the user's role. We will set this user's role to editor.

$user = new TriTan\User((int) $user_id);
$user->set_role('editor');

Send New Account Email

The last thing we need to do is email the user his/her new login details.

$email = func\_ttcms_email();

$message = sprintf(func\_t("<p>Welcome to %s! Here's how to log in: ", 'tritan-cms'), app()->hook->{'get_option'}('sitename'));
$message .= func\get_base_url() . "</p>";
$message .= sprintf(func\_t('Username: %s', 'tritan-cms'), func\_escape($user->user_login)) . "<br />";
$message .= sprintf(func\_t('Password: %s', 'tritan-cms'), $pass) . "<br />";

$_message = func\process_email_html($message, func\_t("New Account", 'tritan-cms'));

$headers[] = sprintf("From: %s <auto-reply@%s>", app()->hook->{'get_option'}('sitename'), func\get_domain_name());
$headers[] = 'Content-Type: text/html; charset="UTF-8"';
$headers[] = sprintf("X-Mailer: TriTan CMS %s", CURRENT_RELEASE);

try {
    $email->ttcmsMail(func\_escape($user->user_email), func\_t('New Account'), $_message, $headers);
} catch (PHPMailer\PHPMailer\Exception $ex) {
    Cascade\Cascade::getLogger('error')->error(sprintf('PHPMailer[%s]: Error: %s', $ex->getCode(), $ex->getMessage()));
}

Ok, now let's put all four parts together in one code block:

/**
 * Import the Functions namespace.
 */
use TriTan\Functions as func;

/**
 * User data used to create a new user.
 */
$data = [
    'user_login' => (string) 'ttcmseditor',
    'user_fname' => (string) 'James',
    'user_lname' => (string) 'Fox',
    'user_email' => (string) 'jfox@ttcmsneweditor.org',
    'user_status' => (string) 'A',
    'user_pass' => (string) $password
];

/**
 * Wrap everything else in an if statement which makes sure
 * the username doesn't already exist. If so, then write it
 * to the error log.
 */
if (!func\username_exists($data['user_login'])) {
    /**
     * Generate a password and create the user.
     */
    $password = func\ttcms_generate_password(12, false);
    $user_id = func\ttcms_insert_user($data);

    /**
     * Grab the last insert id and set the user's role.
     */
    $user = new TriTan\User((int) $user_id);
    $user->set_role('editor');

    /**
     * Create a new Email object, and send user
     * new login details.
     */
    $email = func\_ttcms_email();

    $message = sprintf(func\_t("<p>Welcome to %s! Here's how to log in: ", 'tritan-cms'), app()->hook->{'get_option'}('sitename'));
    $message .= func\get_base_url() . "</p>";
    $message .= sprintf(func\_t('Username: %s', 'tritan-cms'), func\_escape($user->user_login)) . "<br />";
    $message .= sprintf(func\_t('Password: %s', 'tritan-cms'), $pass) . "<br />";

    $_message = func\process_email_html($message, func\_t("New Account", 'tritan-cms'));

    $headers[] = sprintf("From: %s <auto-reply@%s>", app()->hook->{'get_option'}('sitename'), func\get_domain_name());
    $headers[] = 'Content-Type: text/html; charset="UTF-8"';
    $headers[] = sprintf("X-Mailer: TriTan CMS %s", CURRENT_RELEASE);

    try {
        $email->ttcmsMail(func\_escape($user->user_email), func\_t('New Account'), $_message, $headers);
    } catch (PHPMailer\PHPMailer\Exception $ex) {
        Cascade\Cascade::getLogger('error')->error(sprintf('PHPMailer[%s]: Error: %s', $ex->getCode(), $ex->getMessage()));
    }
} else {
    Cascade\Cascade::getLogger('error')->error(sprintf('New User Account: The user %s already exists.', func\_escape($data['user_login'])));
}

Now there are a few things to note and be aware of in the above code, starting from the top and working our way down to the bottom.

First, please note that in order to use some of the TriTan functions, I needed to import the Functions namespace, TriTan\Functions. I then created the alias func, so that it would be easier to type.

Second, whenever possible, use type hinting, especially when saving data.

Third, when setting the user's role, you can use one of three keys: super => Super Administrator, admin => Administrator, and editor => Editor. The system will convert the keys to the corresponding unique id which is saved in the usermeta document.

Fourth, I wrapped the create user and email blocks within an if statement in order to check that the user doesn't exist. It would probably be prudent to check both the username and email address. The else part of the if statement will print a message to the error logs if in fact the user already exists. I suggest checking your error logs or create a queue which will email you every time the error log for a specific day is updated. Use the Run Background Tasks with Nodeq Queue article as an example to follow.

Lastly, when sending the email, I wrapped the sending method in a try/catch block. Every now and again, servers have a hiccup, so catch those messages as often as you can.

Well, that's all folks! What you should do now is look at the Knowledgebase as well as the API Code Docs to familiarize yourself with the many TriTan CMS functions used above.