I have the following in my functions.php file. I'm trying to return a metavalue(s) for a custom post.
add_action( 'transition_post_status', 'a_new_post', 10, 3 );
function a_new_post( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status or 'publish' === $old_status )
return;
if ( 'post' == $post->jobman_job )
return; // all of the above is just to trigger the below when my custom post is published
global $wpdb;
$post_id = $post->ID;
$meta_key_value = 'data19';
$table_name = $wpdb->prefix . 'postmeta';
$result = $wpdb->get_results("SELECT meta_value FROM " . $table_name . " WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key_value);
var_dump ($result); // I'm getting NULL
}
When I use a different query and hardcode the values for $post_id and $meta_key_value into it... I get my result as expected. For some reason, the above query will not accept my variables! Can anybody assist?
Related
I need to automatically create a custom post called 'project' when a logged in user purchased a product.
I put the following code on thank you page:
function get_last_order_id(){
global $wpdb;
$statuses = array_keys(wc_get_order_statuses());
$statuses = implode( "','", $statuses );
// Getting last Order ID (max value)
$results = $wpdb->get_col( "
SELECT MAX(ID) FROM {$wpdb->prefix}posts
WHERE post_type LIKE 'shop_order'
AND post_status IN ('$statuses')
" );
return reset($results);
}
$latest_order_id = get_last_order_id(); // Last order ID
//Auto creation Project post when user purchased
if (!count($latest_order_id)) {
return;
} else {
function programmatically_create_post_after_buying() {
$current_user = wp_get_current_user();
$current_user_id = $current_user->display_name;
$post_id = wp_insert_post(
array(
'author' => $current_user_id,
'post_title' => $current_user_id,
'post_status' => 'publish',
'post_type' => 'project'
)
);
}
add_filter('after_setup_theme', 'programmatically_create_post_after_buying' );
}
The code displays $latest_order_id correctly.
But, it doesn't create a post.
I can't find which parts are wrong, could you please help me?
I am a complete beginner, so there must be a lot of problems.
You can call 'woocommerce_thankyou' action from woocommerce thank you page. By using it you can get latest order id and create post based on that. You can add this code to your theme's functions.php
add_action( 'woocommerce_thankyou', 'create_post_on_order' );
function create_post_on_order( $order_id ){
global $wpdb;
//print('<pre>'.print_r( $wpdb, true ).'</pre>');
$order = wc_get_order( $order_id );
if( !$order->get_id() ){
return;
}
$current_user = wp_get_current_user();
$current_user_id = $current_user->display_name;
$post_title = $order_id.' - '.$current_user_id;
// Check post already exit with our title or not
$query = $wpdb->prepare(
'SELECT ID FROM ' . $wpdb->posts . '
WHERE post_title = %s
AND post_type = \'project\'',
$post_title
);
$wpdb->query( $query );
if ( !$wpdb->num_rows ) {
$post_id = wp_insert_post(
array(
'author' => $current_user_id,
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'project'
)
);
}
}
Note : You have to create post title unique so you can identify post based on order.
I am saving posts by the current user's name. Furthermore, I am saving an array object - $ganalytics_settings - to the post in a custom field. With the following code I am trying to load the array for the username, with a specific post title:
function get_custom_field_for_current_user( $customFieldName ) {
$current_user = wp_get_current_user();
global $wpdb;
$id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $current_user->user_login . "' && post_status = 'draft' && post_type = 'post' ", 'ARRAY_N');
return get_post_meta((int)$id[0], $customFieldName);
}
However, I am getting back the following object:
Instead I would like to get back the following:
Any suggestions why my function gives me back an array in array?
I appreciate your reply!
I don't know if I understood you, but if your function returns the array with first key being an array, then just always return that first key
function get_custom_field_for_current_user( $customFieldName ) {
$current_user = wp_get_current_user();
global $wpdb;
$id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $current_user->user_login . "' && post_status = 'draft' && post_type = 'post' ", 'ARRAY_N');
$post_meta = get_post_meta((int)$id[0], $customFieldName);
return $post_meta[0];
}
The function get_post_meta has the following signature get_post_meta ( int $post_id, string $key = '', bool $single = false ). The return value will be an array if $single is false. Will be value of meta data field if $single is true.
Try this:
function get_custom_field_for_current_user( $customFieldName ) {
$current_user = wp_get_current_user();
global $wpdb;
$id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $current_user->user_login . "' && post_status = 'draft' && post_type = 'post' ", 'ARRAY_N');
return get_post_meta((int)$id[0], $customFieldName, true);
//^ Here to return single value
}
I'm getting the following error in my wordpress dashboard which correlates to a piece of code i've written, however I'm not sure how to fix the error:
Notice: Undefined index: draft in /home/sites/samskirrow.com/public_html/skizzar-test/wp-content/mu-plugins/skizzar-dashboard.php on line 331
Here is the code it's referring to:
/******************************************************************
/* REMOVE BRACKETS AROUND PAGE COUNTS
/******************************************************************/
foreach( array( 'edit-post', 'edit-page', 'edit-movie', 'upload' ) as $hook )
add_filter( "views_$hook" , 'wpse_30331_custom_view_count', 10, 1);
function wpse_30331_custom_view_count( $views )
{
global $current_screen;
switch( $current_screen->id )
{
case 'edit-post':
$views = wpse_30331_manipulate_views( 'post', $views );
break;
case 'edit-page':
$views = wpse_30331_manipulate_views( 'page', $views );
break;
case 'edit-movie':
$views = wpse_30331_manipulate_views( 'movie', $views );
break;
case 'upload':
$views = wpse_30331_manipulate_views( 'attachment', $views );
break;
}
return $views;
}
function wpse_30331_manipulate_views( $what, $views )
{
global $user_ID, $wpdb;
/*
* This is not working for me, 'artist' and 'administrator' are passing this condition (?)
*/
if ( !current_user_can('artist') )
return $views;
/*
* This needs refining, and maybe a better method
* e.g. Attachments have completely different counts
*/
$total = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE (post_status = 'publish' OR post_status = 'draft' OR post_status = 'pending') AND (post_author = '$user_ID' AND post_type = '$what' ) ");
$publish = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = '$user_ID' AND post_type = '$what' ");
$draft = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = '$user_ID' AND post_type = '$what' ");
$pending = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'pending' AND post_author = '$user_ID' AND post_type = '$what' ");
$trash = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'trash' AND post_author = '$user_ID' AND post_type = '$what' ");
/*
* Only tested with Posts/Pages
* - there are moments where Draft and Pending shouldn't return any value
*/
$views['all'] = preg_replace( '/\(.+\)/U', ''.$total.'', $views['all'] );
$views['publish'] = preg_replace( '/\(.+\)/U', ''.$publish.'', $views['publish'] );
$views['draft'] = preg_replace( '/\(.+\)/U', ''.$draft.'', $views['draft'] );
$views['pending'] = preg_replace( '/\(.+\)/U', ''.$pending.'', $views['pending'] );
$views['trash'] = preg_replace( '/\(.+\)/U', ''.$trash.'', $views['trash'] );
return $views;
}
I know that the issue is that certain parameters aren't found in the db (for example, there may not be any "pending" posts) so it throws out an error. How can I code my way around this, for example, to say, if the parameter exists...
The goal here is to remove the '(' ')' brackets from post counts in wordpress. So when you are on the view posts, or view pages screen, there is a sub menu above the lists of posts/pages with the following items 'all', 'published', 'trash', 'pending' - these are filters that the user can click on. Next to each filter is a number, the number of posts/pages within that filter. The format of this count is ([NUMBER]) - This code is to simply get rid of those brackets.
I noticed by google'ing a bit that you're using the code form this Wordpress SE answer. This doesn't match your needs, as this code is here to recalculate the number of posts after some manipulation on that by the OP.
To just remove the parenthesis, look at the following function in class-wp-list-table.php:
public function views() {
$views = $this->get_views();
$views = apply_filters( "views_{$this->screen->id}", $views );
if ( empty( $views ) )
return;
$this->screen->render_screen_reader_content( 'heading_views' );
echo "<ul class='subsubsub'>\n";
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " |</li>\n", $views ) . "</li>\n";
echo "</ul>";
}
This is the function that build the user menu that you try to change. If you look closer at this, you will see that the $view being echo'ed come from a $views that is being filtered previously:
$views = apply_filters( "views_{$this->screen->id}", $views )
$this->screen->id stand for the ID of the current screen, like edit-post for example.
So by adding this simple filter you will achieve what you want to do here:
add_filter('views_edit-post', 'remove_count_parenthesis', 10, 1);
function remove_count_parenthesis($views) {
foreach($views as $key => $view) {
$views[$key] = str_replace(array('(', ')'), '', $view);
}
return $views;
}
You need to check if there is a value 'draft' in your array
if (isset( $views['draft'] )) {
$views['draft'] = preg_replace( '/\(.+\)/U', ''.$draft.'', $views['draft'] );
}
My if ( $filter == 'on' ) in the ugrestriction_filter function seems to not be working in this code when viewing a post. I'm executing this from functions.php It does work when viewing a page. How can I make this work?
Here's my code:
// Join metadata
function ugrestriction_join($join) {
global $wp_query, $wpdb;
$join .= "LEFT JOIN ($wpdb->postmeta) ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
return $join;
}
add_filter('posts_join', 'ugrestriction_join');
// Prevent duplicates
function ugrestriction_distinct( $where ) {
global $wpdb;
return "DISTINCT";
return $where;
}
add_filter( 'posts_distinct', 'ugrestriction_distinct' );
// Filter posts
function ugrestriction_filter( $where, $wp_query )
{
global $wpdb, $post, $current_user, $wp_query;
get_currentuserinfo();
$user_id = $current_user->ID;
$page_id = $wp_query->get_queried_object_id();
$post_id = $post->ID;
$meta_key1 = '_ugrestriction';
$meta_key1_value = 'on';
$postids=$wpdb->get_col( $wpdb->prepare(
"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = 'on'", "_ugrestriction"
) );
//$postids = array("70", "1", "2", "3");
if (in_array($post_id, $postids)) {
$filter = 'on';
} elseif (in_array($page_id, $postids)) {
$filter = 'on';
}
if ( $filter == 'on') {
$where .= " AND ($wpdb->postmeta.meta_key = '_ugrestriction' AND $wpdb->postmeta.meta_value = 'on' AND " . $wpdb->posts . " .post_author =". $user_id .")";
}
return $where;
}
add_filter( 'posts_where', 'ugrestriction_filter', 10, 2 );
From the documentation:
Certain functions which retrieve posts do not run filters, so the
posts_where filter functions you attach will not modify the query. To
overcome this, set suppress_filters to false in the argument array
passed to the function
Source
Have you tried this?
EDIT: More Code.
Problem: I want to get the post meta of a post. It works fine for the case updated_post, but not for new_post and I just can't figure out why..
This is the function for the cases:
function userpro_sc_new_post( $new_status, $old_status, $post ) {
global $userpro_social;
$exclude = userpro_sc_get_option('excluded_post_types');
if ($exclude != ''){
$exclude_types = explode(',',$exclude);
} else {
$exclude_types = array('nav_menu_item');
}
if (!in_array($post->post_type, $exclude_types )) {
// new post
if ( $new_status == 'publish' && $old_status != 'publish' ) {
$user = get_userdata($post->post_author);
$userpro_social->log_action( 'new_post', $user->ID, $post->ID, $post->post_title, $post->post_type );
}
// updated post
if ($new_status == 'publish' && $old_status == 'publish' ){
$user = get_userdata($post->post_author);
$userpro_social->log_action( 'update_post', $user->ID, $post->ID, $post->post_title, $post->post_type );
}
}
}
And this is the code to run in the cases:
function log_action($action, $user_id, $var1=null, $var2=null, $var3=null) {
global $userpro, $userpro_social;
$activity = get_option('userpro_activity');
$timestamp = current_time('timestamp');
$status = '';
switch($action){
case 'new_post':
$myId = get_post_meta(get_the_ID(), 'wpex_post_video_oembed', true);
$status .= $myId;
break;
case 'update_post':
$myId = get_post_meta(get_the_ID(), 'wpex_post_video_oembed', true);
$status .= $myId;
break;
}
Like I said, update_post works so I can see the ID... new_post does not work. Why?
I simplified the code to run a bit, but it is still the same issue.
Please help!
You have to be aware of three things before using get_post_meta() in your plugins.
You must declare global variables as global if any (eg: $wpdb).
You have to get the post data in $post_id (eg: $post_id = $_POST['postid'];).
Update the custom field value if needed (eg: update_post_meta($post_ID, 'video_id', true);).
Any of the above could be your problem. Please refer and try.
global $post;
$avriable_name=get_post_meta($post->ID, 'video_id', true);
Try the above code, global post will help to get the id for the post. If you didnt decalre it $post->ID will be blank and rest will not work.
Please let me know if you need further help.
Try this:
$myId = (get_post_meta(get_the_ID(), 'wpex_post_video_oembed',true));