How to exclude password protected posts in WordPress loop - wordpress

I have a custom post type that supports password protected entries. In a custom loop using a new WP_Query object, I want to exclude those password protected posts from the results. What arguments do I need set in order to do this? I am using the latest trunk version of WordPress 3.2.1.

I come up to this question where I was looking for the same. However, I read WP_Query document line by line then found very simple solution and that is just to add 'has_password' => false argument to the query $args
So the code will be as below...
$args = [
'post_type' => [ 'post', 'page' ],
'posts_per_page' => 3,
'post__not_in' => get_option( 'sticky_posts' ),
'has_password' => FALSE
];
Here you can see I have excluded Sticky and Password Protected posts.

I really like Kevin's approach, but I adjusted it slightly:
// Create a new filtering function that will add our where clause to the query
function my_password_post_filter( $where = '' ) {
// Make sure this only applies to loops / feeds on the frontend
if (!is_single() && !is_admin()) {
// exclude password protected
$where .= " AND post_password = ''";
}
return $where;
}
add_filter( 'posts_where', 'my_password_post_filter' );

Did you take a look at the post_status argument of WP_Query?
"Protected" seems like a good candidate to exclude.
Edit: Okay, it seems like you'll have to modify the where clause to achieve what you want:
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// exclude password protected
$where .= " AND post_password = ''";
return $where;
}
if (!is_single()) { add_filter( 'posts_where', 'filter_where' ); }
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );

After a bit of playing about, I found the posts_where filter a bit too intrusive for what I wanted to do, so I came up with an alternative. As part of the 'save_post' action that I attached for my custom post type, I added the following logic;
$visibility = isset($_POST['visibility']) ? $_POST['visibility'] : '';
$protected = get_option('__protected_posts', array());
if ($visibility === 'password' && !in_array($post->ID, $protected)) {
array_push($protected, $post->ID);
}
if ($visibility === 'public' && in_array($post->ID, $protected)) {
$i = array_search($post->ID, $protected);
unset($protected[$i]);
}
update_option('__protected_posts', $protected);
What this does is hold an array of post id's in the options table where the post is protected by a password. Then in a custom query I simply passed this array as part of the post__not_in option e.g.
$query = new WP_Query(array(
'post_type' => 'my_custom_post_type',
'post__not_in' => get_option('__protected_posts'),
));
This way I could exclude the protected posts from an archive page but still allow a user to land on the password protected page to enter the password.

In addition to #Peter Chester's answer:
You may also want to exclude password-protected posts from the Previous Post and Next Post links, if you have those at the bottom of your post page.
To do so you can add the exclusion to the get_previous_post_where and get_next_post_where hooks.
add_filter( 'get_previous_post_where', 'my_theme_mod_adjacent' );
add_filter( 'get_next_post_where', 'my_theme_mod_adjacent' );
function my_theme_mod_adjacent( $where ) {
return $where . " AND p.post_password = ''";
}

Related

Woocommerce ajax call on single product page

I get all my products from an API and those who are variations to each other all share a custom meta key called "api_product_family". The products with the same api_product_family are variants to each other, so on the single page I have a hook where I display the other variants with image and anchor to it's variants.
My code:
function mv_variations() {
global $post;
global $wpdb;
$product_id = $post->ID;
$product_family = get_post_meta( $post->ID, 'api_product_family', true );
if(!empty($product_family)) {
$query = "
SELECT post_id
FROM " . $wpdb->prefix . "postmeta
WHERE meta_value = '" . $product_family . "'
";
$products = $wpdb->get_col($query);
if(count($products) > 0) {
for($i=0; $i<count($products); $i++) {
if($products[$i] == $product_id) {
unset($products[$i]);
}
}
if(count($products) > 0) {
print '<h3>Choose other variants: </h3>';
foreach($products as $product) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id($product));
print '<img src="' . $image[0] . '" alt="img"/> ';
}
}
}
}
}
add_action( 'woocommerce_single_product_summary', 'mv_variations' );
The problem:
I have a LOT of posts, and a lot of post_meta's, so it's taking an eternity to load so I was thinking to move this whole function inside and AJAX call so it's doesn't slow down the initial load. The problem is that I have no idea how to do that with wordpress
Are you simply looking to run a WP function via AJAX?
1) Add ajax actions
This needs to run inside the main plugin file. If you run this only on the public code, it will not work. WP is a little weird and all ajax uses admin-ajax.php
if ( wp_doing_ajax() ){
add_action( 'wp_ajax_yourcustomfunction', array($this, 'yourcustomfunction') );
add_action( 'wp_ajax_nopriv_yourcustomfunction', array($this, 'yourcustomfunction') );
}
function yourcustomfunction(){
echo 'success';
exit();
}
2) In JavaScript
in the backend, you have the global: ajaxurl for the ajax url
BUT in the front end you need to pass this as a variable via wp_localize_script
$datatoBePassed = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'your_javascript_script', 'plugin_display_settings', $datatoBePassed );
In JS:
var datavar = {
action: 'yourcustomfunction',
};
$.post(plugin_display_settings.ajaxurl, datavar, function(response){
//response received here. It will be 'success' which is echoed in PHP
});
3)
If you also want to run a security nonce check (to check the request truly originates from the WP website, prevents some attacks), it gets a little more complicated:
$datatoBePassed should also include 'security' => wp_create_nonce( 'yourplugin_security_nonce' ),
datavar in JS includes security: plugin_display_settings.security,
Finally, your PHP custom function begins with:
// Check security nonce.
if ( ! check_ajax_referer( 'yourplugin_security_nonce', 'security' ) ) {
wp_send_json_error( 'Invalid security token sent.' );
wp_die();
}
// If security check passed, run further
So I think you might get better performance using WP_Query. Below I converted what you have into a custom WP_Query. May need some slight adjustment but should be the right direction.
function mv_variations() {
global $post_id;
// get current post "product family"
$product_family = get_post_meta( $post_id, 'api_product_family', true );
// build related "product family" products query
$products_query_args = array(
'post_type' => 'product', // may need to update this for your case
'posts_per_page' => -1, // return all found
'post__not_in' => array($post_id), // exclude current post
'post_status' => 'publish',
// use a meta query to pull only posts with same "product family" as current post
'meta_query' => array(
array(
'key' => 'api_product_family',
'value' => $product_family,
'compare' => '='
)
)
);
$products_query = new WP_Query($products_query);
// use "the loop" to display your products
if ( $products_query->have_posts() ) :
print '<h3>Choose other variants: </h3>';
while ( $products_query->have_posts() ) : $products_query->the_post();
print ''. wp_get_attachment_image() .'';
endwhile;
// restore global post
wp_reset_postdata();
endif;
}
add_action( 'woocommerce_single_product_summary', 'mv_variations' );

WP REST API orderby meta_value

Need to be able to sort the results of a REST API custom post query by a meta value.
Having difficulty doing so.
I have made my post type available to the REST API and can order by the Date, Title, etc...
But when I try the Post Meta it doesn't work.
I have added the following code to try and enable the functionality but defaults to ordering by date.
function my_add_meta_vars ($current_vars) {
$current_vars = array_merge ($current_vars, array('meta_key', 'meta_value'));
return $current_vars;
}
add_filter ('query_vars', 'my_add_meta_vars');
add_filter ('rest_query_vars', 'my_add_meta_vars');
My REST API query is
mysite.com/wp-json/wp/v2/hh_equipment?filter[orderby]=meta_value_num&meta_key=equipment_price&order=desc
I have tried following the instructions here to no avail.
Running WordPress 4.8 and tried testing on 4.7 to no avail
I've got it working with the rest_' . $post_type . '_collection_params filter and rest_' . $post_type . '_query filter like so (change $post_type to needed post type slug):
// Add meta your meta field to the allowed values of the REST API orderby parameter
add_filter(
'rest_' . $post_type . '_collection_params',
function( $params ) {
$params['orderby']['enum'][] = 'YOUR_META_KEY';
return $params;
},
10,
1
);
// Manipulate query
add_filter(
'rest_' . $post_type . '_query',
function ( $args, $request ) {
$order_by = $request->get_param( 'orderby' );
if ( isset( $order_by ) && 'YOUR_META_KEY' === $order_by ) {
$args['meta_key'] = $order_by;
$args['orderby'] = 'meta_value'; // user 'meta_value_num' for numerical fields
}
return $args;
},
10,
2
);
The first filter adds your meta field to the possible values of the ordeby parameters, as by default REST API supports only: author, date, id, include, modified, parent, relevance, slug, include_slugs, title (check the ordeby param in the WP REST API handbook)
The second filter allows you to manipulate the query that returns the results when you have your meta key inside the orderby. Here we need to reset orderby to 'meta_value' or 'meta_value_num' (read more about this in WP Query class description) and set the meta key to your custom field key.
Refer below method,
I modified the existing routes to add a new args entry which validates the meta_key values which are permitted. No need to modify the rest query vars this way either.
add_filter('rest_endpoints', function ($routes) {
// I'm modifying multiple types here, you won't need the loop if you're just doing posts
foreach (['some', 'types'] as $type) {
if (!($route =& $routes['/wp/v2/' . $type])) {
continue;
}
// Allow ordering by my meta value
$route[0]['args']['orderby']['enum'][] = 'meta_value_num';
// Allow only the meta keys that I want
$route[0]['args']['meta_key'] = array(
'description' => 'The meta key to query.',
'type' => 'string',
'enum' => ['my_meta_key', 'another key'],
'validate_callback' => 'rest_validate_request_arg',
);
}
return $routes;
});
REF: https://github.com/WP-API/WP-API/issues/2308

Override a function with child themes functions.php

As the title reads I'm trying to modify a function called by a parent theme in my child, I know that the child theme is set to be loaded beforehand so I'm curious if this is even possible?
My parent theme has a function called ajax_search_box() that I'd like to modify a query in, and I'd rather not modify the parent theme files in case I need to update it down the road.. what would be the best way to do this?
Also, for bonus points, how would I go about doing this with a widget as well? Thanks in advance!
function SearchFilter($query) {
// If 's' request variable is set but empty
if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
$query->is_search = true;
$query->is_home = false;
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
function ajax_search_box() {
if (isset($_GET["q"]))
{
$q = $_GET["q"];
global $wpdb;
$q = mysql_real_escape_string($q);
$q = $wpdb->escape($q);
$query = array(
'post_status' => 'publish',
'order' => 'DESC',
's' => $q
);
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );
// Check if any posts were found.
if ( ! $get_posts->post_count )
die();
//Create an array with the results
foreach ( $posts as $post )
echo $post->post_title . "|" . $post->ID . "\n";
}
die();
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_ajax_search_box', 'ajax_search_box' );
add_action( 'wp_ajax_ajax_search_box', 'ajax_search_box' );
the parent theme needs to check if(function_exists('ajax_search_box')) and if it doesn't exist then it will declare it.
If the parent theme checks to see if the function exists, then you can declare it first and have it do what you want.
If the parent theme does not check, get in touch with the theme author to see if they will throw that change in for the next update....and code it yourself too. That way when the theme updates then you will still be good to go.
Break free of functions.php, write your own plugin.
<?php
/**
* Plugin Name: Manipulate the Parent
* Requires: PHP5.3+
*/
add_action( 'after_setup_theme', function()
{
remove_filter( 'pre_get_posts','SearchFilter' );
// now add your own filter
add_filter( 'pre_get_posts', 'your_callback_for_your_filter' );
});
function your_callback_for_your_filter()
{
// do stuff
}

Removing Content with wp_delete_post in a Plugin with Custom Post Type

I set up a plugin that adds a custom post type and then brings in a bunch of dummy content with wp_insert_post on activation like so:
register_activation_hook( __FILE__, array( $this, 'activate' ) );
public function activate( $network_wide ) {
include 'dummycontent.php';
foreach ($add_posts_array as $post){
wp_insert_post( $post );
};
} // end activate
I would like to remove this content when the plugin is deactivated so I set up this function:
register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );
public function deactivate( $network_wide ) {
include 'dummycontent.php';
foreach($remove_posts_array as $array){
$page_name = $array["post_title"];
global $wpdb;
$page_name_id = $wpdb->get_results("SELECT ID FROM " . $wpdb->base_prefix . "posts WHERE post_title = '". $page_name ."'");
foreach($page_name_id as $page_name_id){
$page_name_id = $page_name_id->ID;
wp_delete_post( $page_name_id, true );
};
};
} // end deactivate
It works just fine. Except because the custom post type is created with the same plugin that these two functions are run through, the post type is removed before the posts themselves can be through wp_delete_post. When I test these functions out without the custom post type posts are added upon activation and removed upon deactivation. So I know the problem is with the post type. Does anyone know how to work around this?
Try something like this (YOUTPOSTTYPE is the name of your post type):
function deactivate () {
$args = array (
'post_type' => 'YOURPOSTTYPE',
'nopaging' => true
);
$query = new WP_Query ($args);
while ($query->have_posts ()) {
$query->the_post ();
$id = get_the_ID ();
wp_delete_post ($id, true);
}
wp_reset_postdata ();
}
It works in my plugin, it should works in your's. (This has been tested with WordPress 3.5.1).
wp_delete_post($ID, false) sends it to Trash. Only when you remove from Trash is a post really deleted. That's why it works with $force = true.
So it works as expected. First posts go to Trash, then they get actually deleted. Like Recycle Bin. Trace the post_status change to see when it hits the Trash if you want to do anything then. Otherwise wait for the delete.
Also delete content on uninstall and not on deactivate. Consider deactivating a plugin as pausing it and uninstalling it when you really want it gone.
Try this Function
function deactivate () {
$args = array(
'post_type' => 'POST_TYPE',
'posts_per_page' => - 1
);
if ( $posts = get_posts( $args ) ) {
foreach ( $posts as $post ) {
wp_delete_post( $post->ID, true );
}
}
}

Wordpress how to prevent duplicate post by checking if post title exist before running "wp_insert_post"?

I have a wordpress site that connects to a soap server. The problem is every time I run the script the wp_insert_post is using the same result again.
I would like to check if existing post_title matches the value from $title then if they match, prevent wp_insert_post from using the same value again.
Here's the code:
try {
$client = new SoapClient($wsdl, array('login' => $username, 'password' => $password));
} catch(Exception $e) {
die('Couldn\'t establish connection to weblink service.');
}
$publications = $client->GetPublicationSummaries();
foreach ($publications->GetPublicationSummariesResult->PublicationSummaries->PublicationSummary as $publication_summary) {
// get the complete publication from the webservice
$publication = $client->getPublication(array('PublicationId' => $publication_summary->ID))->GetPublicationResult->Publication;
// get all properties and put them in an array
$properties = array();
foreach ($publication->Property as $attribute => $value) {
$properties[$attribute] = $value;
}
// Assemble basic title from properties
$title = $properties['Address']->Street . ' ' . $properties['Address']->HouseNumber . $properties['Address']->HouseNumberExtension . ', ' . $properties['Address']->City->_;
}
$my_post = array(
'post_title'=>$title,
'post_content'=>'my contents',
'post_status'=>'draft',
'post_type'=>'skarabeepublication',
'post_author'=>1,
);
wp_insert_post($my_post);
Thank you for any help.
You can use get_page_by_title() as it supports custom post types now.
if (!get_page_by_title($title, OBJECT, 'skarabeepublication')) :
$my_post = array(
'post_title'=>$title,
'post_content'=>'my contents',
'post_status'=>'draft',
'post_type'=>'skarabeepublication',
'post_author'=>1,
);
wp_insert_post($my_post);
endif;
Codex information here
Surprised not to see mention of post_exists function in wp-includes/post.php. See entry on wpseek. There is no entry in the codex. At it's simplest it works like get_page_by_title but returns a post id (or 0 if not found) instead of the object (or null).
$post_id = post_exists( $my_title );
if (!$post_id) {
// code here
}
Sorry for the late response. I used what Robot says in the comment and this solved my problem. Thanks
$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title like '$title_from_soap'");
if($post_if < 1){
//code here
}
sampler:
if( !get_page_by_path('mypageslug',OBJECT,'post') ){
//your codes
}

Resources