Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WordPress] Using Direct Database Queries to Quickly Update Data, Part 2
<?php
/**
* Locates all of the post IDs that are associated with an empty meta key (which
* is specified as an argument for the function).
*
* @param string $metaKey The meta key used to retrieve the set of post IDs.
* @return array $results The set of product IDs associated with the specified meta key.
*/
public function getInactivePostIds(string $metaKey) : array
{
global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare(
"
SELECT post_id
FROM $wpdb->postmeta
WHERE meta_key = %s
AND meta_value = ''
",
$metaKey
)
);
return $results;
}
<?php
/**
* Updates incoming posts by setting their post status to 'draft.'
*
* @param array $postData the set of post IDs associated with the specific meta key.
*/
public function setPostsToDraft(array $postData)
{
// If the post data is empty, there's nothing to do.
if (0 === \count($postData)) {
return;
}
// Otherwise, set the post_status of the specified post IDs to 'draft'.
global $wpdb;
foreach ($postData as $post) {
$wpdb->get_results(
$wpdb->prepare(
"
UPDATE $wpdb->posts
SET post_status = %s
WHERE ID = %d
",
'draft',
(int) ($post->post_id)
)
);
}
}
<?php
$postStatusModifier = new PostStatusModifier();
$inactivePost = $postStatusModifier->getInactivePostIds('acme-status');
$postStatusModifier->setPostsToDraft($inactivePosts);
<?php
class PostStatusModifier
{
/**
* Locates all of the post IDs that are associated with an empty meta key (which
* is specified as an argument for the function).
*
* @param string $metaKey The meta key used to retrieve the set of post IDs.
* @return array $results The set of product IDs associated with the specified meta key.
*/
public function getInactivePostIds(string $metaKey) : array
{
global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare(
"
SELECT post_id
FROM $wpdb->postmeta
WHERE meta_key = %s
AND meta_value = ''
",
$metaKey
)
);
return $results;
}
/**
* Updates incoming posts by setting their post status to 'draft.'
*
* @param array $postData the set of post IDs associated with the specific meta key.
*/
public function setPostsToDraft(array $postData)
{
// If the post data is empty, there's nothing to do.
if (0 === \count($postData)) {
return;
}
// Otherwise, set the post_status of the specified post IDs to 'draft'.
global $wpdb;
foreach ($postData as $post) {
$wpdb->get_results(
$wpdb->prepare(
"
UPDATE $wpdb->posts
SET post_status = %s
WHERE ID = %d
",
'draft',
(int) ($post->post_id)
)
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.