Reading array from custom fields - php

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
}

Related

Wordpress undefined index issue php

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'] );
}

$wpdb->get_results not accepting variable in query

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?

if logic in posts_where not working wordpress

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?

WordPress count user posts of different custom post types

I've been looking for a way to count the number of custom posts a user has created, and was able to do it using this snippet:
<?php
$userid = get_current_user_id();
function count_user_posts_by_type($userid, $post_type = 'foo_type', $post_status = 'publish') {
global $wpdb;
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND post_type = '$post_type' AND post_status = '$post_status'";
$count = $wpdb->get_var($query);
return apply_filters('get_usernumposts', $count, $userid);
} ?>
And then echo the result with:
<?php echo count_user_posts_by_type($userid); ?>
My question: Above code outputs only the count of the custom post type "foo_type". If I have two custom post types - "foo_type" and "bar_type" - how do I change this code so that it returns the count of both of them rather than just the count of "foo_type"?
Add the second post_type to the query:
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND (post_type = '$post_type' OR post_type='$post_type_2') AND post_status = '$post_status'";
Try custom function given below
function my_count_posts_by_user($post_author=null,$post_type=array(),$post_status=array()) {
global $wpdb;
if(empty($post_author))
return 0;
$post_status = (array) $post_status;
$post_type = (array) $post_type;
$sql = $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = %d AND ", $post_author );
//Post status
if(!empty($post_status)){
$argtype = array_fill(0, count($post_status), '%s');
$where = "(post_status=".implode( " OR post_status=", $argtype).') AND ';
$sql .= $wpdb->prepare($where,$post_status);
}
//Post type
if(!empty($post_type)){
$argtype = array_fill(0, count($post_type), '%s');
$where = "(post_type=".implode( " OR post_type=", $argtype).') AND ';
$sql .= $wpdb->prepare($where,$post_type);
}
$sql .='1=1';
$count = $wpdb->get_var($sql);
return $count;
}
And then echo the result with:
<?php echo my_count_posts_by_user($userid , array('posttype1' , 'posttype2')); ?>
Please look on url given below..
https://wordpress.stackexchange.com/questions/43549/count-user-posts-by-user-id-post-type-and-post-status
thanks
$args = array(
'post_type'=> 'page',
'author' => '1',
'post_staus'=> 'publish',
'posts_per_page' => -1
);
echo custom_count_post_by_author($args);
function custom_count_post_by_author($args){
query_posts( $args );
$count = 0;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$count++;
endwhile;
endif;
wp_reset_query();
return $count;
}
You can pass any Arguments in $args which support query_posts

wordpress tag archive, sort order with custom post type

I added this code added to funtions.php
function tc_tag_for_cpt($query) {
if(is_tag() && empty( $query->query_vars['suppress_filters'] ) && !is_admin()) {
$post_type = get_query_var('post_type');
$post_type = ($post_type) ? $post_type : array('resources','post','page'); //,'nav_menu_item'
$query->set('post_type',$post_type);
return $query;
}
}
add_filter( 'posts_orderby', 'sort_query_by_post_type', 10, 2 );
function sort_query_by_post_type( $sortby, $thequery ) {
if(is_tag() && empty( $query->query_vars['suppress_filters'] ) && !is_admin()) {
$thequery->set('orderby','post_type');
if ( !empty($thequery->query_vars['post_type']) && isset($thequery->query_vars['orderby']) && $thequery->query_vars['orderby'] == 'post_type' )
$sortby = "find_in_set(post_type, '" . implode( ',', $thequery->query_vars['post_type'] ) . "')";
}
return $sortby;
}
which is supposed to display results on the tag archive sorted by post type (resources is a custom post type).
It does this but an error message appears on the top of the screen:
"Warning: implode() [function.implode]: Invalid arguments passed in /home/csleh3/public_html/sandbox/wp-content/themes/aodmarketing/functions.php on line 279"
which is the "implode" line.
My goal is to have the results on the tag archive sort the list by post type, not date or title.
$thequery->query_vars['post_type'] will return the specific post_type as a string like post. You can't implode that.
You should just be able to remove the part about trying to implode it:
$sortby = "find_in_set(post_type, '" . $thequery->query_vars['post_type'] . "')";

Categories