php 使用短代码按用户ID计算已发布产品的数量。使用短代码的示例[my-products id ='1']。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 使用短代码按用户ID计算已发布产品的数量。使用短代码的示例[my-products id ='1']。相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Plugin Name: Get Count Publish Products by User ID
 * Plugin URI: https://gist.github.com/campusboy87/71c8849656b4b8e1fd1702cdf41d6d51
 * Author: Campusboy
 */

// Example of using a shortcode [my-products id='1']
add_shortcode( 'my-products', 'get_count_published_products_by_user_id_shortcode' );

/**
 * @param array $atts
 *
 * @return string
 */
function get_count_published_products_by_user_id_shortcode( $atts ) {
	$atts = shortcode_atts( array(
		'id' => 0,
	), $atts );

	$id_user = intval( $atts['id'] );

	if ( ! $id_user ) {
		return 'Укажите ID пользователя!';
	}

	$count = get_count_published_products_by_user_id( $id_user );

	return $count > 0 ? "Products published - $count" : 'No published products';
}

/**
 * @param int $user_id
 *
 * @return int
 */
function get_count_published_products_by_user_id( $user_id ) {
	global $wpdb;

	$count = intval( $wpdb->get_var( "
		SELECT COUNT(ID) 
		FROM $wpdb->posts 
		WHERE post_type = 'product' AND post_status = 'publish' AND post_author = $user_id
	" ) );

	return $count;
}

以上是关于php 使用短代码按用户ID计算已发布产品的数量。使用短代码的示例[my-products id ='1']。的主要内容,如果未能解决你的问题,请参考以下文章