Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added method to find by given meta property value #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,37 @@ public static function get_searchable_fields()
{
return ['post_title', 'post_content', 'post_excerpt'];
}

/**
* Find a specific model by a given meta property value.
*
* @param string $property
* @param string $value
* @return false|self
*/
public static function find_one_by_meta($property, $value)
{
global $wpdb;

// Escape the value
$value = esc_sql($value);

// Get the table name
$table = static::get_table();

$meta_subquery = " (
SELECT post_id
FROM `".$wpdb->postmeta."`
WHERE (
meta_key = '".$property."'
AND meta_value = '".esc_sql($value)."'
)
) ";

// Get the item
$obj = $wpdb->get_row("SELECT * FROM `{$table}` WHERE `ID` = ".$meta_subquery, ARRAY_A);

// Return false if no item was found, or a new model
return ($obj ? static::create($obj) : false);
}
}