WPDb

This module should be used in acceptance and functional tests, see levels of testing for more information. This module extends the Db module adding WordPress-specific configuration parameters and methods. The module provides methods to read, write and update the WordPress database directly, without relying on WordPress methods, using WordPress functions or triggering WordPress filters.

Backup your content

This module, like the Codeception Db one it extends, by default will load a databse dump in the database it's using. This means that the database contents will be replaced by the dump contents on each run of a suite using the module. You can set the populate and cleanup parameters to false to prevent this default behavior but it's usually not what you need in an automated test. Make a backup of any database you're using in tests that contains any information you care about before you run any test!

Change the databse used depending on whether you're running tests or not

The chore of having to plug different databases, or backup them, depending on whether you're manually testing the site or automatically testing can be mitigated switching them automatically depending on the browser user agent or request headers. This module was born to be used in acceptance and functional tests (see levels of testing for more information) and will often be coupled with modules like the WPBrowser one or the WPWebDriver one. Depending on which of the two modules is being used in the suite there are different ways to automate the "database switching".

Automatically changing database based on the browser user agent

If you would like to automate the "switching above" below you will find an example setup. Update the test site wp-config.php file from this:

define( 'DB_NAME', 'wordpress' );

to this:

<?php
if (
// Custom header.
isset( $_SERVER['HTTP_X_TESTING'] )
// Custom user agent.
|| ( isset( $_SERVER['HTTP_USER_AGENT'] ) && $_SERVER['HTTP_USER_AGENT'] === 'wp-browser' )
// The env var set by the WPClIr or WordPress modules.
|| getenv( 'WPBROWSER_HOST_REQUEST' )
) {
// Use the test database if the request comes from a test.
define( 'DB_NAME', 'wordpress_test' );
} else {
// Else use the default one.
define( 'DB_NAME', 'wordpress' );
}

If you're using the WPWebDriver module set the user agent in the browser, in this example I'm setting the user agent in Chromedriver:

class_name: AcceptanceTester
modules:
enabled:
- \Helper\Acceptance
- WPDb
- WPWebDriver
config:
WPDb:
dsn: 'mysql:host=%WP_DB_HOST%;dbname=%WP_DB_NAME%'
user: %WP_DB_USER%
password: %WP_DB_PASSWORD%
dump: tests/_data/dump.sql
populate: true
cleanup: false
url: '%WP_URL%'
tablePrefix: %WP_TABLE_PREFIX%
urlReplacement: true
WPWebDriver:
url: '%WP_URL%'
adminUsername: '%WP_ADMIN_USERNAME%'
adminPassword: '%WP_ADMIN_PASSWORD%'
adminPath: '%WP_ADMIN_PATH%'
browser: chrome
host: localhost
port: 4444
window_size: false
wait: 5
capabilities:
# Used in more recent releases of Selenium.
"goog:chromeOptions":
args: ["--no-sandbox", "--headless", "--disable-gpu", "--user-agent=wp-browser"]
# Support the old format for back-compatibility purposes.
"chromeOptions":
args: ["--no-sandbox", "--headless", "--disable-gpu", "--user-agent=wp-browser"]

If you're using the WPBrowser module send a specific header in the context of test requests:

class_name: AcceptanceTester
modules:
enabled:
- \Helper\Acceptance
- WPDb
- WPBrowser
config:
WPDb:
dsn: 'mysql:host=%DB_HOST%;dbname=%WP_DB_NAME%'
user: %WP_DB_USER%
password: %WP_DB_PASSWORD%
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
reconnect: false
url: '%WP_URL%'
tablePrefix: 'wp_'
WPBrowser:
url: '%WP_URL%'
adminUsername: 'admin'
adminPassword: 'admin'
adminPath: '/wp-admin'
headers:
X-Testing: 'wp-browser'

Configuration

  • dsn required - the database POD DSN connection details; read more on PHP PDO documentation.

  • user required - the database user.

  • password required - the database password.

  • url required - the full URL, including the HTTP scheme, of the website whose database is being accessed. WordPress uses hard-codece URLs in the databas, that URL will be set by this module when applying the SQL dump file during population or cleanup.

  • dump required - defaults to null; sets the path, relative to the project root folder, or absolute to the SQL dump file that will be used to set the tests initial database fixture. If set to null then the populate, cleanup and populator parameters will be ignored.

  • populate - defaults to true to empty the target database and import the SQL dump specified in the dump argument once, before any test starts.

  • cleanup - defaults to true empty the target database and import the SQL dump specified in the dump argument before each test starts.

  • urlReplacement - defaults to true to replace, while using the built-in, PHP-based, dump import solution the hard-coded WordPress URL in the database with the specified one.

  • populator - defaults to null, if set to an executable shell command then that command will be used to populate the database in place of the built-in PHP solution; URL replacement will not apply in this case. Read more about this on Codeception documentation.

  • reconnect - defaults to true to force the module to reconnect to the database before each test in place of only connecting at the start of the tests.

  • waitlock - defaults to 10; wait lock (in seconds) that the database session should use for DDL statements.

  • tablePrefix - defaults to wp_; sets the prefix of the tables that the module will manipulate.

Example configuration

modules:
enabled:
- WPDb
config:
WPDb:
dsn: 'mysql:host=localhost;dbname=wordpress'
user: 'root'
password: 'password'
dump: 'tests/_data/dump.sql'
populate: true
cleanup: true
waitlock: 10
url: 'http://wordpress.localhost'
urlReplacement: true
tablePrefix: 'wp_'

Using the module with the WPLoader one

This module is often used in conjunction with the WPLoader one to use WordPress-defined functions, classes and methods in acceptance or functional tests. The WPLoader module should be set to only load WordPress and this module should be listed, in the modules.eanbled section of the suite configuration file before the WPLoader one:

modules:
enabled:
- WPDb # this before...
- WPLoader # ...this one.
config:
WPDb:
# ...
WPLoader:
loadOnly: true
# ...

This will avoid issues where the WPLoader module could exit, terminating the test run, due to an inconsistent database state.

Public API

countRowsInDatabase

Returns the number of table rows matching a criteria.

$I->haveManyPostsInDatabase(3, ['post_status' => 'draft' ]);
$I->haveManyPostsInDatabase(3, ['post_status' => 'private' ]);
// Make sure there are now the expected number of draft posts.
$postsTable = $I->grabPostsTableName();
$draftsCount = $I->countRowsInDatabase($postsTable, ['post_status' => 'draft']);

Parameters

  • string $table - The table to count the rows in.

  • array $criteria - Search criteria, if empty all table rows will be counted.

dontHaveAttachmentFilesInDatabase

Removes all the files attached with an attachment post, it will not remove the database entries. Requires the WPFilesystem module to be loaded in the suite.

$posts = $I->grabPostsTableName();
$attachmentIds = $I->grabColumnFromDatabase($posts, 'ID', ['post_type' => 'attachment']);
// This will only remove the files, not the database entries.
$I->dontHaveAttachmentFilesInDatabase($attachmentIds);

Parameters

  • array/int $attachmentIds - An attachment post ID or an array of attachment post IDs.

dontHaveAttachmentInDatabase

Removes an attachment from the posts table.

$postmeta = $I->grabpostmetatablename();
$thumbnailId = $I->grabFromDatabase($postmeta, 'meta_value', [
'post_id' => $id,
'meta_key'=>'thumbnail_id'
]);
// Remove only the database entry (including postmeta) but not the files.
$I->dontHaveAttachmentInDatabase($thumbnailId);
// Remove the database entry (including postmeta) and the files.
$I->dontHaveAttachmentInDatabase($thumbnailId, true, true);

Parameters

  • array $criteria - An array of search criteria to find the attachment post in the posts table.

  • bool $purgeMeta - If set to true then the meta for the attachment will be purged too.

  • bool $removeFiles - Remove all files too, requires the WPFilesystem module to be loaded in the suite.

dontHaveBlogInDatabase

Removes one ore more blogs frome the database.

// Remove the blog, all its tables and files.
$I->dontHaveBlogInDatabase(['path' => 'test/one']);
// Remove the blog entry, not the tables though.
$I->dontHaveBlogInDatabase(['blog_id' => $blogId]);
// Remove multiple blogs.
$I->dontHaveBlogInDatabase(['domain' => 'test']);

Parameters

  • array $criteria - An array of search criteria to find the blog rows in the blogs table.

  • bool $removeTables - Remove the blog tables.

  • bool $removeUploads - Remove the blog uploads; requires the WPFilesystem module.

dontHaveCommentInDatabase

Removes an entry from the comments table.

$I->dontHaveCommentInDatabase(['comment_post_ID' => 23, 'comment_url' => 'http://example.copm']);

Parameters

  • array $criteria - An array of search criteria.

  • bool $purgeMeta - If set to true then the meta for the comment will be purged too.

dontHaveCommentMetaInDatabase

Removes a post comment meta from the database

// Remove all meta for the comment with an ID of 23.
$I->dontHaveCommentMetaInDatabase(['comment_id' => 23]);
// Remove the `count` comment meta for the comment with an ID of 23.
$I->dontHaveCommentMetaInDatabase(['comment_id' => 23, 'meta_key' => 'count']);

Parameters

  • array $criteria - An array of search criteria.

dontHaveInDatabase

Deletes a database entry.

$I->dontHaveInDatabase('custom_table', ['book_ID' => 23, 'book_genre' => 'fiction']);

Parameters

  • string $table - The table name.

  • array $criteria - An associative array of the column names and values to use as deletion criteria.

dontHaveLinkInDatabase

Removes a link from the database.

$I->dontHaveLinkInDatabase(['link_url' => 'http://example.com']);

Parameters

  • array $criteria - An array of search criteria.

dontHaveOptionInDatabase

Removes an entry from the options table.

// Remove the `foo` option.
$I->dontHaveOptionInDatabase('foo');
// Remove the 'bar' option only if it has the `baz` value.
$I->dontHaveOptionInDatabase('bar', 'baz');

Parameters

  • string $key - The option name.

  • null/mixed $value - If set the option will only be removed if its value matches the passed one.

dontHavePostInDatabase

Removes an entry from the posts table.

$posts = $I->haveManyPostsInDatabase(3, ['post_title' => 'Test {{n}}']);
$I->dontHavePostInDatabase(['post_title' => 'Test 2']);

Parameters

  • array $criteria - An array of search criteria.

  • bool $purgeMeta - If set to true then the meta for the post will be purged too.

dontHavePostMetaInDatabase

Removes an entry from the postmeta table.

$postId = $I->havePostInDatabase(['meta_input' => ['rating' => 23]]);
$I->dontHavePostMetaInDatabase(['post_id' => $postId, 'meta_key' => 'rating']);

Parameters

  • array $criteria - An array of search criteria.

dontHaveSiteOptionInDatabase

Removes a site option from the database.

// Remove the `foo_count` option.
$I->dontHaveSiteOptionInDatabase('foo_count');
// Remove the `foo_count` option only if its value is `23`.
$I->dontHaveSiteOptionInDatabase('foo_count', 23);

Parameters

  • string $key - The option name.

  • null/mixed $value - If set the option will only be removed it its value matches the specified one.

dontHaveSiteTransientInDatabase

Removes a site transient from the database.

$I->dontHaveSiteTransientInDatabase(['my_plugin_site_buffer']);

Parameters

  • string $key - The name of the transient to delete.

dontHaveTableInDatabase

Removes a table from the database. The case where a table does not exist is handled without raising an error.

$ordersTable = $I->grabPrefixedTableNameFor('orders');
$I->dontHaveTableInDatabase($ordersTable);

Parameters

  • string $fullTableName - The full table name, including the table prefix.

dontHaveTermInDatabase

Removes a term from the database.

$I->dontHaveTermInDatabase(['name' => 'romance']);
$I->dontHaveTermInDatabase(['slug' => 'genre--romance']);

Parameters

  • array $criteria - An array of search criteria.

  • bool $purgeMeta - Whether the terms meta should be purged along side with the meta or not.

dontHaveTermMetaInDatabase

Removes a term meta from the database.

// Remove the "karma" key.
$I->dontHaveTermMetaInDatabase(['term_id' => $termId, 'meta_key' => 'karma']);
// Remove all meta for the term.
$I->dontHaveTermMetaInDatabase(['term_id' => $termId]);

Parameters

  • array $criteria - An array of search criteria.

dontHaveTermRelationshipInDatabase

Removes an entry from the term_relationships table.

// Remove the relation between a post and a category.
$I->dontHaveTermRelationshipInDatabase(['object_id' => $postId, 'term_taxonomy_id' => $ttaxId]);
// Remove all terms for a post.
$I->dontHaveTermMetaInDatabase(['object_id' => $postId]);

Parameters

  • array $criteria - An array of search criteria.

dontHaveTermTaxonomyInDatabase

Removes an entry from the term_taxonomy table.

// Remove a specific term from the genre taxonomy.
$I->dontHaveTermTaxonomyInDatabase(['term_id' => $postId, 'taxonomy' => 'genre']);
// Remove all terms for a taxonomy.
$I->dontHaveTermTaxonomyInDatabase(['taxonomy' => 'genre']);

Parameters

  • array $criteria - An array of search criteria.

dontHaveTransientInDatabase

Removes a transient from the database.

// Removes the `tweets` transient from the database, if set.
$I->dontHaveTransientInDatabase('tweets');

Parameters

  • string $transient - The name of the transient to delete.

dontHaveUserInDatabase

Removes a user from the database.

$bob = $I->haveUserInDatabase('bob');
$alice = $I->haveUserInDatabase('alice');
// Remove Bob's user and meta.
$I->dontHaveUserInDatabase('bob');
// Remove Alice's user but not meta.
$I->dontHaveUserInDatabase($alice);

Parameters

  • int/string $userIdOrLogin - The user ID or login name.

  • bool $purgeMeta - Whether the user meta should be purged alongside the user or not.

dontHaveUserInDatabaseWithEmail

Removes a user(s) from the database using the user email address.

$luca = $I->haveUserInDatabase('luca', 'editor', ['user_email' => 'luca@example.org']);

Parameters

  • string $userEmail - The email of the user to remove.

  • bool $purgeMeta - Whether the user meta should be purged alongside the user or not.

dontHaveUserMetaInDatabase

Removes an entry from the usermeta table.

// Remove the `karma` user meta for a user.
$I->dontHaveUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);
// Remove all the user meta for a user.
$I->dontHaveUserMetaInDatabase(['user_id' => 23]);

Parameters

  • array $criteria - An array of search criteria.

dontSeeAttachmentInDatabase

Checks that an attachment is not in the database.

$url = 'https://example.org/images/foo.png';
$I->dontSeeAttachmentInDatabase(['guid' => $url]);

Parameters

  • array $criteria - An array of search criteria.

dontSeeBlogInDatabase

Checks that a row is not present in the blogs table.

$I->haveManyBlogsInDatabase(2, ['path' => 'test-{{n}}'], false)
$I->dontSeeBlogInDatabase(['path' => '/test-3/'])

Parameters

  • array $criteria - An array of search criteria.

dontSeeCommentInDatabase

Checks that a comment is not in the database. Will look up the "comments" table.

// Checks for one comment.
$I->dontSeeCommentInDatabase(['comment_ID' => 23]);
// Checks for comments from a user.
$I->dontSeeCommentInDatabase(['user_id' => 89]);

Parameters

  • array $criteria - The serach criteria.

dontSeeCommentMetaInDatabase

Checks that a comment meta value is not in the database. Will look up the "commentmeta" table.

// Delete a comment `karma` meta.
$I->dontSeeCommentMetaInDatabase(['comment_id' => 23, 'meta_key' => 'karma']);
// Delete all meta for a comment.
$I->dontSeeCommentMetaInDatabase(['comment_id' => 23]);

Parameters

  • array $criteria - An array of search criteria.

dontSeeLinkInDatabase

Checks that a link is not in the links database table.

$I->dontSeeLinkInDatabase(['link_url' => 'http://example.com']);
$I->dontSeeLinkInDatabase(['link_url' => 'http://example.com', 'link_name' => 'example']);

Parameters

  • array $criteria - An array of search criteria.

dontSeeOptionInDatabase

Checks that an option is not in the database for the current blog. If the value is an object or an array then the serialized option will be checked.

$I->dontHaveOptionInDatabase('posts_per_page');
$I->dontSeeOptionInDatabase('posts_per_page');

Parameters

  • array $criteria - An array of search criteria.

dontSeePageInDatabase

Checks that a page is not in the database.

// Assert a page with an ID does not exist.
$I->dontSeePageInDatabase(['ID' => 23]);
// Assert a page with a slug and ID.
$I->dontSeePageInDatabase(['post_name' => 'test', 'ID' => 23]);

Parameters

  • array $criteria - An array of search criteria.

dontSeePostInDatabase

Checks that a post is not in the database.

// Asserts a post with title 'Test' is not in the database.
$I->dontSeePostInDatabase(['post_title' => 'Test']);
// Asserts a post with title 'Test' and content 'Test content' is not in the database.
$I->dontSeePostInDatabase(['post_title' => 'Test', 'post_content' => 'Test content']);

Parameters

  • array $criteria - An array of search criteria.

dontSeePostMetaInDatabase

Checks that a post meta value does not exist. If the meta value is an object or an array then the check will be made on its serialized version.

$postId = $I->havePostInDatabase(['meta_input' => ['foo' => 'bar']]);
$I->dontSeePostMetaInDatabase(['post_id' => $postId, 'meta_key' => 'woot']);

Parameters

  • array $criteria - An array of search criteria.

dontSeePostWithTermInDatabase

Checks that a post to term relation does not exist in the database. The method will check the "term_relationships" table.

$fiction = $I->haveTermInDatabase('fiction', 'genre');
$nonFiction = $I->haveTermInDatabase('non-fiction', 'genre');
$postId = $I->havePostInDatabase(['tax_input' => ['genre' => ['fiction']]]);
$I->dontSeePostWithTermInDatabase($postId, $nonFiction['term_taxonomy_id], );
passed this parameter will be interpreted as a `term_id`, else as a
the
term order.
to build a `taxonomy_term_id` from the `term_id`.

Parameters

  • int $post_id - The post ID.

  • int $term_taxonomy_id - The term term_id or term_taxonomy_id; if the $taxonomy argument is

  • int/null $term_order - The order the term applies to the post, defaults to null to not use

  • string/null $taxonomy - The taxonomy the term_id is for; if passed this parameter will be used

dontSeeTableInDatabase

Checks that a table is not in the database.

$options = $I->grabPrefixedTableNameFor('options');
$I->dontHaveTableInDatabase($options)
$I->dontSeeTableInDatabase($options);

Parameters

  • string $table - The full table name, including the table prefix.

dontSeeTermInDatabase

Makes sure a term is not in the database. Looks up both the terms table and the term_taxonomy tables.

// Asserts a 'fiction' term is not in the database.
$I->dontSeeTermInDatabase(['name' => 'fiction']);
// Asserts a 'fiction' term with slug 'genre--fiction' is not in the database.
$I->dontSeeTermInDatabase(['name' => 'fiction', 'slug' => 'genre--fiction']);

Parameters

  • array $criteria - An array of criteria to search for the term, can be columns from the terms and the

dontSeeTermMetaInDatabase

Checks that a term meta is not in the database.

list($termId, $termTaxonomyId) = $I->haveTermInDatabase('fiction', 'genre');
$I->haveTermMetaInDatabase($termId, 'rating', 4);
$I->dontSeeTermMetaInDatabase(['term_id' => $termId,'meta_key' => 'average_review']);

Parameters

  • array $criteria - An array of search criteria.

dontSeeTermTaxonomyInDatabase

Checks that a term taxonomy is not in the database.

list($termId, $termTaxonomyId) = $I->haveTermInDatabase('fiction', 'genre');
$I->dontSeeTermTaxonomyInDatabase(['term_id' => $termId, 'taxonomy' => 'country']);

Parameters

  • array $criteria - An array of search criteria.

dontSeeUserInDatabase

Checks that a user is not in the database.

// Asserts a user does not exist in the database.
$I->dontSeeUserInDatabase(['user_login' => 'luca']);
// Asserts a user with email and login is not in the database.
$I->dontSeeUserInDatabase(['user_login' => 'luca', 'user_email' => 'luca@theaveragedev.com']);

Parameters

  • array $criteria - An array of search criteria.

dontSeeUserMetaInDatabase

Check that a user meta value is not in the database.

// Asserts a user does not have a 'karma' meta assigned.
$I->dontSeeUserMetaInDatabase(['user_id' => 23, 'meta_key' => 'karma']);
// Asserts no user has any 'karma' meta assigned.
$I->dontSeeUserMetaInDatabase(['meta_key' => 'karma']);

Parameters

  • array $criteria - An array of search criteria.

getSiteDomain

Returns the site domain inferred from the url set in the config.

$domain = $I->getSiteDomain();
// We should be redirected to the HTTPS version when visiting the HTTP version.
$I->amOnPage('http://' . $domain);
$I->seeCurrentUrlEquals('https://' . $domain);

getUsersTableName

Returns the prefixed users table name.

// Given a `wp_` table prefix returns `wp_users`.
$usersTable = $I->getUsersTableName();
// Given a `wp_` table prefix returns `wp_users`.
$I->useBlog(23);
$usersTable = $I->getUsersTableName();

grabAllFromDatabase

Returns all entries matching a criteria from the database.

$books = $I->grabPrefixedTableNameFor('books');
$I->grabAllFromDatabase($books, 'title', ['genre' => 'fiction']);

Parameters

  • string $table - The table to grab the values from.

  • string $column - The column to fetch.

  • array $criteria - The search criteria.

grabAttachmentAttachedFile

Returns the path, as stored in the database, of an attachment _wp_attached_file meta. The attached file is, usually, an attachment origal file.

$file = $I->grabAttachmentAttachedFile($attachmentId);
$fileInfo = new SplFileInfo($file);
$I->assertEquals('jpg', $fileInfo->getExtension());

Parameters

  • int $attachmentPostId - The attachment post ID.

grabAttachmentMetadata

Returns the metadata array for an attachment post. This is the value of the _wp_attachment_metadata meta.

$metadata = $I->grabAttachmentMetadata($attachmentId);
$I->assertEquals(['thumbnail', 'medium', 'medium_large'], array_keys($metadata['sizes']);

Parameters

  • int $attachmentPostId - The attachment post ID.

grabBlogDomain

Returns a blog domain given its ID.

$blogIds = $I->haveManyBlogsInDatabase(3);
$domains = array_map(function($blogId){
return $I->grabBlogDomain($blogId);
}, $blogIds);

Parameters

  • int $blogId - The blog ID.

grabBlogPath

Grabs a blog domain from the blogs table.

$blogId = $I->haveBlogInDatabase('test');
$path = $I->grabBlogDomain($blogId);
$I->amOnSubdomain($path);
$I->amOnPage('/');

Parameters

  • int $blogId - The blog ID.

grabBlogTableName

Returns the full name of a table for a blog from a multisite installation database.

$blogOptionTable = $I->grabBlogTableName($blogId, 'option');

Parameters

  • int $blogId - The blog ID.

  • string $table - The table name, without table prefix.

grabBlogTableNames

Returns a list of tables for a blog ID.

$blogId = $I->haveBlogInDatabase('test');
$tables = $I->grabBlogTableNames($blogId);
$options = array_filter($tables, function($tableName){
return str_pos($tableName, 'options') !== false;
});

Parameters

  • int $blogId - The ID of the blog to fetch the tables for.

grabBlogTablePrefix

Returns the table prefix for a blog.

$blogId = $I->haveBlogInDatabase('test');
$blogTablePrefix = $I->getBlogTablePrefix($blogId);
$blogOrders = $I->blogTablePrefix . 'orders';

Parameters

  • int $blogId - The blog ID.

grabBlogVersionsTableName

Gets the prefixed blog_versions table name.

// Assuming a `wp_` table prefix it will return `wp_blog_versions`.
$blogVersionsTable = $I->grabBlogVersionsTableName();
$I->useBlog(23);
// Assuming a `wp_` table prefix it will return `wp_blog_versions`.
$blogVersionsTable = $I->grabBlogVersionsTableName();

grabBlogsTableName

Gets the prefixed blogs table name.

// Assuming a `wp_` table prefix it will return `wp_blogs`.
$blogVersionsTable = $I->grabBlogsTableName();
$I->useBlog(23);
// Assuming a `wp_` table prefix it will return `wp_blogs`.
$blogVersionsTable = $I->grabBlogsTableName();

grabCommentmetaTableName

Returns the prefixed comment meta table name.

// Get all the values of 'karma' for all comments.
$commentMeta = $I->grabCommentmetaTableName();
$I->grabAllFromDatabase($commentMeta, 'meta_value', ['meta_key' => 'karma']);

grabCommentsTableName

Gets the comments table name.

// Will be `wp_comments`.
$comments = $I->grabCommentsTableName();
// Will be `wp_23_comments`.
$I->useBlog(23);
$comments = $I->grabCommentsTableName();

grabLatestEntryByFromDatabase

Returns the id value of the last table entry.

$I->haveManyPostsInDatabase();
$postsTable = $I->grabPostsTableName();
$last = $I->grabLatestEntryByFromDatabase($postsTable, 'ID');
items.

Parameters

  • string $tableName - The table to fetch the last insertion for.

  • string $idColumn - The column that is used, in the table, to uniquely identify

grabLinksTableName

Returns the prefixed links table name.

// Given a `wp_` table prefix returns `wp_links`.
$linksTable = $I->grabLinksTableName();
// Given a `wp_` table prefix returns `wp_23_links`.
$I->useBlog(23);
$linksTable = $I->grabLinksTableName();

grabOptionFromDatabase

Gets an option value from the database.

$count = $I->grabOptionFromDatabase('foo_count');

Parameters

  • string $option_name - The name of the option to grab from the database.

grabPostMetaFromDatabase

Gets the value of one or more post meta values from the database.

$thumbnail_id = $I->grabPostMetaFromDatabase($postId, '_thumbnail_id', true);

Parameters

  • int $postId - The post ID.

  • string $metaKey - The key of the meta to retrieve.

  • bool $single - Whether to return a single meta value or an arrya of all available meta values.

grabPostmetaTableName

Returns the prefixed post meta table name.

// Returns 'wp_postmeta'.
$I->grabPostmetaTableName();
// Returns 'wp_23_postmeta'.
$I->useBlog(23);
$I->grabPostmetaTableName();

grabPostsTableName

Gets the posts prefixed table name.

// Given a `wp_` table prefix returns `wp_posts`.
$postsTable = $I->grabPostsTableName();
// Given a `wp_` table prefix returns `wp_23_posts`.
$I->useBlog(23);
$postsTable = $I->grabPostsTableName();

grabPrefixedTableNameFor

Returns a prefixed table name for the current blog. If the table is not one to be prefixed (e.g. users) then the proper table name will be returned.

// Will return wp_users.
$usersTable = $I->grabPrefixedTableNameFor('users');
// Will return wp_options.
$optionsTable = $I->grabPrefixedTableNameFor('options');
// Use a different blog and get its options table.
$I->useBlog(2);
$blogOptionsTable = $I->grabPrefixedTableNameFor('options');

Parameters

  • string $tableName - The table name, e.g. options.

grabRegistrationLogTableName

Gets the prefixed registration_log table name.

// Assuming a `wp_` table prefix it will return `wp_registration_log`.
$blogVersionsTable = $I->grabRegistrationLogTableName();
$I->useBlog(23);
// Assuming a `wp_` table prefix it will return `wp_registration_log`.
$blogVersionsTable = $I->grabRegistrationLogTableName();

grabSignupsTableName

Gets the prefixed signups table name.

// Assuming a `wp_` table prefix it will return `wp_signups`.
$blogVersionsTable = $I->grabSignupsTableName();
$I->useBlog(23);
// Assuming a `wp_` table prefix it will return `wp_signups`.
$blogVersionsTable = $I->grabSignupsTableName();

grabSiteMetaTableName

Gets the prefixed sitemeta table name.

// Assuming a `wp_` table prefix it will return `wp_sitemeta`.
$blogVersionsTable = $I->grabSiteMetaTableName();
$I->useBlog(23);
// Assuming a `wp_` table prefix it will return `wp_sitemeta`.
$blogVersionsTable = $I->grabSiteMetaTableName();

grabSiteOptionFromDatabase

Gets a site option from the database.

$fooCountOptionId = $I->haveSiteOptionInDatabase('foo_count','23');

Parameters

  • string $key - The name of the option to read from the database.

grabSiteTableName

Gets the prefixed site table name.

// Assuming a `wp_` table prefix it will return `wp_site`.
$blogVersionsTable = $I->grabSiteTableName();
$I->useBlog(23);
// Assuming a `wp_` table prefix it will return `wp_site`.
$blogVersionsTable = $I->grabSiteTableName();

grabSiteTransientFromDatabase

Gets a site transient from the database.

$I->grabSiteTransientFromDatabase('total_comments');
$I->grabSiteTransientFromDatabase('api_data');

Parameters

  • string $key - The site transient to fetch the value for, w/o the _site_transient_ prefix.

grabSiteUrl

Returns the current site URL as specified in the module configuration.

$shopPath = $I->grabSiteUrl('/shop');

Parameters

  • string $path - A path that should be appended to the site URL.

grabTablePrefix

Returns the table prefix, namespaced for secondary blogs if selected.

// Assuming a table prefix of `wp_` it will return `wp_`;
$tablePrefix = $I->grabTablePrefix();
$I->useBlog(23);
// Assuming a table prefix of `wp_` it will return `wp_23_`;
$tablePrefix = $I->grabTablePrefix();

grabTermIdFromDatabase

Gets a term ID from the database. Looks up the prefixed terms table, e.g. wp_terms.

// Return the 'fiction' term 'term_id'.
$termId = $I->grabTermIdFromDatabase(['name' => 'fiction']);
// Get a term ID by more stringent criteria.
$termId = $I->grabTermIdFromDatabase(['name' => 'fiction', 'slug' => 'genre--fiction']);
// Return the 'term_id' of the first term for a group.
$termId = $I->grabTermIdFromDatabase(['term_group' => 23]);

Parameters

  • array $criteria - An array of search criteria.

grabTermMetaTableName

Gets the terms meta table prefixed name.

// Returns 'wp_termmeta'.
$I->grabTermMetaTableName();
// Returns 'wp_23_termmeta'.
$I->useBlog(23);
$I->grabTermMetaTableName();

grabTermRelationshipsTableName

Gets the prefixed term relationships table name, e.g. wp_term_relationships.

$I->grabTermRelationshipsTableName();

grabTermTaxonomyIdFromDatabase

Gets a term_taxonomy_id from the database. Looks up the prefixed terms_relationships table, e.g. wp_term_relationships.

// Get the `term_taxonomy_id` for a term and a taxonomy.
$I->grabTermTaxonomyIdFromDatabase(['term_id' => $fictionId, 'taxonomy' => 'genre']);
// Get the `term_taxonomy_id` for the first term with a count of 23.
$I->grabTermTaxonomyIdFromDatabase(['count' => 23]);

Parameters

  • array $criteria - An array of search criteria.

grabTermTaxonomyTableName

Gets the prefixed term and taxonomy table name, e.g. wp_term_taxonomy.

// Returns 'wp_term_taxonomy'.
$I->grabTermTaxonomyTableName();
// Returns 'wp_23_term_taxonomy'.
$I->useBlog(23);
$I->grabTermTaxonomyTableName();

grabTermsTableName

Gets the prefixed terms table name, e.g. wp_terms.

// Returns 'wp_terms'.
$I->grabTermsTableName();
// Returns 'wp_23_terms'.
$I->useBlog(23);
$I->grabTermsTableName();

grabUserIdFromDatabase

Gets the a user ID from the database using the user login.

$userId = $I->grabUserIdFromDatabase('luca');

Parameters

  • string $userLogin - The user login name.

grabUserMetaFromDatabase

Gets a user meta from the database.

// Returns a user 'karma' value.
$I->grabUserMetaFromDatabase($userId, 'karma');
// Returns an array, the unserialized version of the value stored in the database.
$I->grabUserMetaFromDatabase($userId, 'api_data');

Parameters

  • int $userId - The ID of th user to get the meta for.

  • string $meta_key - The meta key to fetch the value for.

grabUsermetaTableName

Returns the prefixed users meta table name.

// Given a `wp_` table prefix returns `wp_usermeta`.
$usermetaTable = $I->grabUsermetaTableName();
// Given a `wp_` table prefix returns `wp_usermeta`.
$I->useBlog(23);
$usermetaTable = $I->grabUsermetaTableName();

grabUsersTableName

Returns the prefixed users table name.

// Given a `wp_` table prefix returns `wp_users`.
$usersTable = $I->grabUsersTableName();
// Given a `wp_` table prefix returns `wp_users`.
$I->useBlog(23);
$usersTable = $I->grabUsersTableName();

haveAttachmentInDatabase

Creates the database entries representing an attachment and moves the attachment file to the right location.

$file = codecept_data_dir('images/test.png');
$attachmentId = $I->haveAttachmentInDatabase($file);
$image = codecept_data_dir('images/test-2.png');
$lastWeekAttachment = $I->haveAttachmentInDatabase($image, '-1 week');
Requires the WPFilesystem module.
should be used to build the "year/time" uploads sub-folder structure.
image sizes created by default.

Parameters

  • string $file - The absolute path to the attachment file.

  • string/string/int $date - Either a string supported by the strtotime function or a UNIX timestamp that

  • array $overrides - An associative array of values overriding the default ones.

  • array $imageSizes - An associative array in the format [ => [,]] to override the

haveBlogInDatabase

Inserts a blog in the blogs table.

// Create the `test` subdomain blog.
$blogId = $I->haveBlogInDatabase('test', ['administrator' => $userId]);
// Create the `/test` subfolder blog.
$blogId = $I->haveBlogInDatabase('test', ['administrator' => $userId], false);
or subfolder (`true`)

Parameters

  • string $domainOrPath - The subdomain or the path to the be used for the blog.

  • array $overrides - An array of values to override the defaults.

  • bool $subdomain - Whether the new blog should be created as a subdomain (true)

haveCommentInDatabase

Inserts a comment in the database.

$I->haveCommentInDatabase($postId, ['comment_content' => 'Test Comment', 'comment_karma' => 23]);

Parameters

  • int $comment_post_ID - The id of the post the comment refers to.

  • array $data - The comment data overriding default and random generated values.

haveCommentMetaInDatabase

Inserts a comment meta field in the database. Array and object meta values will be serialized.

$I->haveCommentMetaInDatabase($commentId, 'api_ID', 23);
// The value will be serialized.
$apiData = ['ID' => 23, 'user' => 89, 'origin' => 'twitter'];
$I->haveCommentMetaInDatabase($commentId, 'api_data', $apiData);

Parameters

  • int $comment_id - The ID of the comment to insert the meta for.

  • string $meta_key - The key of the comment meta to insert.

  • mixed $meta_value - The value of the meta to insert, if serializable it will be serialized.

haveLinkInDatabase

Inserts a link in the database.

$linkId = $I->haveLinkInDatabase(['link_url' => 'http://example.org']);

Parameters

  • array $overrides - The data to insert.

haveManyBlogsInDatabase

Inserts many blogs in the database.

$blogIds = $I->haveManyBlogsInDatabase(3, ['domain' =>'test-{{n}}']);
foreach($blogIds as $blogId){
$I->useBlog($blogId);
$I->haveManuPostsInDatabase(3);
}

Parameters

  • int $count - The number of blogs to create.

  • array $overrides - An array of values to override the default ones; {{n}} will be replaced by the count.

  • bool $subdomain - Whether the new blogs should be created as a subdomain or subfolder.

haveManyCommentsInDatabase

Inserts many comments in the database.

// Insert 3 random comments for a post.
$I->haveManyCommentsInDatabase(3, $postId);
// Insert 3 random comments for a post.
$I->haveManyCommentsInDatabase(3, $postId, ['comment_content' => 'Comment {{n}}']);

Parameters

  • int $count - The number of comments to insert.

  • int $comment_post_ID - The comment parent post ID.

  • array $overrides - An associative array to override the defaults.

haveManyLinksInDatabase

Inserts many links in the database links table.

// Insert 3 randomly generated links in the database.
$linkIds = $I->haveManyLinksInDatabase(3);
// Inserts links in the database replacing the `n` placeholder.
$linkIds = $I->haveManyLinksInDatabase(3, ['link_url' => 'http://example.org/test-{{n}}']);

Parameters

  • int $count - The number of links to insert.

  • array $overrides - Overrides for the default arguments.

haveManyPostsInDatabase