$_POST in array? - php

I have a script that put some terms into an array and then into the database.
Below you find a snippet. Everything is working fine, but i cannot get the $POST code to work correctly. What i need is that it contains the value of 'app' combined with the $album['id'] that is submitted by a form. I am pretty sure I am doing something wrong here. Can anyone help me out? Thanks.
global $wpdb;
$post_id = get_queried_object_id();
$post_author_id = get_post_field( 'post_author', $post_id );
$albums = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM wp_wppa_albums WHERE owner = "' . get_author_name( $post_author_id ) .'"' ), ARRAY_A );
$input_terms = array();
if ( $albums ) foreach( $albums as $album ) {
$input_terms[] = 'app_'.$_POST[$album['id']]; //This goes wrong
}

Whoops, my bad. Was an easy fix
$input_terms[] = sanitize_text_field($_POST['app_'.$album['id']]);
Worked for me!

Related

How to let users post only once for custom post type (php / wordpress)?

I need to let users only post once for custom post 'projects'.
The code below counts the number of the post:
$userid = get_current_user_id();
function count_user_posts_by_type($userid, $post_type = 'projects', $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 shows correct number with
<?php echo count_user_posts_by_type($userid); ?>
My question:
I need to combine it with add_action.
So that when the result is 0 the user can post, when the result is !=0 the user cannot post.
The code below is something that I want to implement but it doesn't work at all and I have no idea how to combine together.
Would you please let me know how to combine codes together?
add_action( 'count-user-posts-by-type', 'count_user_posts_by_type' );
$postcount = count_user_posts_by_type($userid);
if($postcount != 0){
return ( 'www.mywebsite.com/cannot-post/' );
} else{
return ( 'www.mywebsite.com/can-post/' );
}
}
Thank you.
You can use is_user_logged_in() to check whether the current user is logged in or not.
Then you can use the template_redirect hook to perform the check :
function only_post_once_redirect()
{
if( is_user_logged_in() ) {
$userid = get_current_user_id(); //-- get the user id
$postcount = count_user_posts_by_type( $userid ); //-- get the count
if( $postcount != 0 ){ //-- not equal to zero
wp_redirect( home_url( 'www.mywebsite.com/cannot-post/' ) );
die;
} else{ //-- equal to zero
wp_redirect( home_url( 'www.mywebsite.com/can-post/' ) );
die;
}
}
}
add_action( 'template_redirect', 'only_post_once_redirect' );
You may need to add some more login to it, say to check which the user is now or something like that.
Or if you want this check & redirect to happen just after the login, you could try the login_redirect hook.
EDIT
I believe you have to spend some time polishing your PHP skills. Look for some basic PHP tutorials like this. You will recall everything after you spend an hour or two in those tutorials.
To answer your question(which you asked in comments), you can simply pass the second parameter as string. No need of that $post_type = part in it. Only in function definition (ie, when you define how the function should perform), you write the default values. When you make function calls, you simply pass the values as parameter. No need of the assignments in the parameters.
In short, your function call should be like this:
$postcount = count_user_posts_by_type( $userid2, 'projects' );
Since you've already mentioned the default value of the second parameter to be projects in your function definition, you can simply use this:
$postcount = count_user_posts_by_type( $userid2 );
I solved the problem using different code, in case someone needs it :
add_shortcode( 'current-user-has-posts' , 'current_user_has_posts' );
function current_user_has_posts(){
$args = array(
'post_type' => 'projects',
'author' => get_current_user_id(),
);
$wp_posts = get_posts($args);
if (count($wp_posts)) {
return ( 'www.mywebsite.com/cannot-post/' );
} else {
return ( 'www.mywebsite.com/can-post/' );
}
}

Include post title wordpress in replace SQL

I need something similar to this:
$titulo = get_the_title( $post_id );
update wp_posts set post_content =
replace(post_content,'>Episódio','>$titulo Episódio');
I know that this function is wrong, but it is a way of exemplifying what I need.
I need to get the title wordpress and use with the SQL replace function
Backup your database first before trying this. Add this to your theme's 'functions.php', run only once and delete. Please note that this will replace all occurrences of 'Episodio' with '[post title] Episodio'. Keep FTP in hand since you may not able to access 'functions.php' before deleting this code.
<?php
function replace_string()
{
global $wpdb;
$table_name = $wpdb->prefix . "posts";
$results = $wpdb->get_results ( "SELECT * FROM $table_name ORDER BY ID" );
foreach ( $results as $postobj )
{
$post_content = str_replace( 'Episodio', $postobj->post_title.' Episodio', $postobj->post_content);
$selectd = "UPDATE {$table_name} SET `post_content` = '".$post_content."' WHERE ID='".$postobj->ID."'";
$wpdb->get_results($selectd);
}
die();
}
add_action( 'after_setup_theme', 'replace_string' );
?>

Wordpress query posts by title issue

I'm using below code to get posts by title.
protected function get_post_by_title($post_title, $output = OBJECT, $post_type = 'post' )
{
global $wpdb;
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $post_title, $post_type ));
if ( $post )
return get_page($post, $output);
return null;
}
Everything is working fine, except it will not find the posts having single quote in title. Consider below as $post_title.
This is a test's post
$wpdb->prepare will return query something like below.
This is a test\\\'s post
Which will return no result. Can anyone please help me on this ?
Thanks in advance
You should never compare with the real title. Wordpress offers you the possibility to create slugs without all those weird characters like " " or "'". Then you can compare them:
Use sanitize_title() to create a slug from your title, and then you can compare them.
I think this should fix the issue,
DOC: http://in1.php.net/manual/en/mysqli.real-escape-string.php
protected function get_post_by_title($post_title, $output = OBJECT, $post_type = 'post' )
{
global $wpdb;
$post_title = mysqli_real_escape_string($post_title); //escape special meaning
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $post_title, $post_type ));
if ( $post )
return get_page($post, $output);
return null;
}
edit:
That might not work, try this,
$post_title = addslashes($post_title);
Let me know which one works for you.

Wordpress - Show only posts with specific slug

I'm sure this is going to be a silly question... but here it goes.
I currently have a page that only displays posts of a Custom Post Type (car).
I do this by running a query
$args = array(
'post_type' => 'car');
$query = new WP_Query( $args );
On to the loop...
For this Custom Post Type i have a Custom Taxonomy e.g. Subaru, Honda etc...
I'm just trying to work something else out, but if I wanted to show only posts that are Subaru's, how would I query that?
I guess I want to query the 'slug' (subaru), this code doesn't work, but you can see the route I was heading...
$args = array(
'name' => 'subaru',
'post_type' => 'car');
$query = new WP_Query( $args );
On to the loop...
I know name isn't right. What is the correct term to add to my $args array?
Many thanks
Depends on what your taxonomy is called. In my example its called 'brands':
$args = array(
'post_type' => 'car',
'brand' => 'subaru'
);
$query = new WP_Query( $args );
see http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
What you're trying to do is a taxonomy query. I could tell you how to do that but I think it's important I point out a much bigger mistake first. You shouldn't querying this on a page.
That's what archives are for.
Create a template file called archive-car.php and output there instead. That removes the need to run a custom WP Query.
Then create another file taxonomy-{your-custom-taxonomy-name}.php
Output the cars there as well and your problem is solved without adding any inefficient queries.
I think you need to use get_terms()
$terms = get_terms("Subaru");
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
echo "<ul>";
foreach ( $terms as $term ) {
echo "<li>" . $term->name . "</li>";
}
echo "</ul>";
}
See this http://codex.wordpress.org/Function_Reference/get_terms

Return all values stored in var outside foreach loop

So I assume something is being overwritten but I am unsure as to how to stop this and retrieve all values outside loop. Any ideas?
foreach($gallids as $gallterm)
{
$postterms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
$checkmissing = $postterms[0];
print_r($checkmissing); // Check Terms for missing images - works here.
}
print_r($checkmissing); // Check Terms for missing images - not working here
// - seems to be getting last or first val only.
First of all initialize the variable you want to use later on:
$checkmissing = array();
Then inside the foreach append the first entry of the post terms to that array:
foreach($gallids as $gallterm)
{
list($checkmissing[]) = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
}
See $checkmissing[], that is what effectively will prevent that you overwrite it. It will append each to the array.
Finally you can output the result after the loop:
print_r($checkmissing);
Note: You should do some additional handling if wp_get_post_terms returns an empty array:
foreach($gallids as $gallterm)
{
$terms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"))
AND list($checkmissing[]) = $terms
;
}
I tried a few of the examples above and they didn't quite work the way I wanted. So I poked around and did a little research, here's how I got it working for me.
In my particular case I needed to grab all the category ID's for a specific post, then return that variable into the WP_Query arguments array.
First, you will need to grab the post terms
$terms = get_the_terms( $post->ID, 'category' );
Next you'll want to initialize the variable you want to use later on:
$cat_terms = array();
Next you'll declare the foreach to get each individual term ID
foreach ( $terms as $term ) {
$cat_terms[] = $term->term_id;
}
Now let's say you want to use return a comma separated list for this $cat_terms variable. We're going to use the 'join' function
$comma_separated_terms = join( ", ", $cat_terms );
Now let's say you want to use this variable to put into you WP_Query loop for say the 'category__in' parameter. We're going to use 'array_values'.
$values = array_values($cat_terms);
The nice thing about this is now we can insert this $values variable into the WP_Query arguments:
<?php global $post;
$query = new WP_Query(array(
'post_type' => 'post_type_name',
'category__in' => $values));
?>
In my particular case, the client wanted some custom post types to display in the sidebar based on the blog posts categories. So I needed to get all the blog post terms and match them up with the terms for the custom post types categories.
Final Code Looked something like this:
<?php
$terms = get_the_terms( $post->ID, 'category' );
$cat_terms = array();
foreach ( $terms as $term ) {
$cat_terms[] = $term->term_id;
}
$values = array_values($cat_terms);
?>
<h3><?php echo $title; ?></h3>
<?php global $post;
$query = new WP_Query(array(
'post_type' => 'custom_post_type',
'category__in' => $values));
if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
// Code for loop goes here
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
$checkmissing = array();
foreach($gallids as $gallterm)
{
$postterms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
$checkmissing[] = $postterms[0];
print_r($checkmissing); // Check Terms for missing images - works here.
}
print_r($checkmissing); // Check Terms for missing images
// will get all missing images as array
foreach($gallids as $gallterm) {
$postterms = wp_get_post_terms( $gallterm, 'type', array("fields" => "slugs") );
$checkmissing[] = $postterms[0];
}
print_r($checkmissing); //Now this will be a 2d array with all your values..
$checkmissing = array();
$i=1;
foreach($gallids as $gallterm)
{
$postterms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
$checkmissing[$i] = $postterms[0];
//print_r($checkmissing); // Check Terms for missing images - works here.
$i++;
}
print_r($checkmissing);

Categories