Wordpress - GD Star Rating - Set Rating after wp_insert_post - wordpress

is it possbile to rate the new post (with admin account) after this?
$post_id = wp_insert_post( $my_post, $wp_error );

According to this post of the Wordpress support forum, what you should do is something like this:
function set_rating($post_id, $vote) { // $vote = 0..10
$admin = get_user_by('login', 'admin');
if ($admin !== false) {
$ip = $_SERVER['SERVER_ADDR'];
$ua = $_SERVER['HTTP_USER_AGENT'];
gdsrBlgDB::save_vote($post_id, $admin->ID, $ip, $ua, $vote);
}
return $admin;
}

You need to add a hook after that happens. First write a function and then this:
add_action('wp_insert_post', 'set_star_rating');
function set_star_rating() {
global $post;
$post = ...
}
There is also save_posts hook which happens while you're saving the post and is better documented.

This may be useful for doing some custom development based on GD Star Rating Plugin. Find my functions to 'save post like', to get 'like count for a post' and to 'check whether current user liked a post'. This is working for custom Post Types as well.
/**
* Function to save post like
* #param type $post_id
* #param type $user_id
*/
function save_post_like($post_id, $user_id) {
$ip = $_SERVER['SERVER_ADDR'];
$ua = $_SERVER['HTTP_USER_AGENT'];
if(has_user_liked_post($post_id) == 0)
gdsrBlgDB::save_vote_thumb($post_id, $user_id, $ip, $ua, 1);
}
/**
* Function to check if user like the post
* #global type $wpdb
* #global type $table_prefix
* #param type $post_id
* #return type
*/
function has_user_liked_post($post_id) {
global $wpdb, $table_prefix;
$userdata = wp_get_current_user();
$user_id = is_object($userdata) ? $userdata->ID : 0;
$sql = "SELECT * FROM " . $table_prefix . "gdsr_votes_log WHERE vote_type = 'artthumb' AND id = " . $post_id . " AND user_id = " . $user_id;
$results = $wpdb->get_row($sql, OBJECT);
if (count($results))
return 1;
else
return 0;
}
/**
* Function to get total Likes of a Post
* #global type $wpdb
* #global type $table_prefix
* #param type $post_id
* #return type
*/
function get_post_like_count($post_id) {
global $wpdb, $table_prefix;
$sql = "SELECT * FROM " . $table_prefix . "gdsr_data_article WHERE post_id = " . $post_id;
$results = $wpdb->get_row($sql, OBJECT);
if (count($results))
return $results->user_recc_plus;
else
return 0;
}

Related

Snippet load only one page?

How to make that snippet using (Code Snippet in Wordpress) load only one page, because of home page and other pages loading time.
The code I'm using:
'''add_action( 'init', 'register_uzleteim_endpoint');
/**
* Register New Endpoint.
*
* #return void.
*/
function register_uzleteim_endpoint(){
add_rewrite_endpoint( 'uzleteim', EP_ROOT | EP_PAGES );
}
add_filter( 'query_vars', 'uzleteim_query_vars' );
/**
* Add new query var.
*
* #param array $vars vars.
*
* #return array An array of items.
*/
function uzleteim_query_vars( $vars ) {
$vars[] = 'uzleteim';
return $vars;
}
add_filter( 'woocommerce_account_menu_items', 'add_uzleteim_tab' );
/**
* Add New tab in my account page.
*
* #param array $items myaccount Items.
*
* #return array Items including New tab.
*/
function add_uzleteim_tab( $items ) {
$items['uzleteim'] = 'Üzleteim';
return $items;
}
add_action( 'woocommerce_account_uzleteim_endpoint', 'add_uzleteim_content' );
/**
* Add content to the new tab.
*
* #return string.
*/
function add_uzleteim_content() {}
I'm already tried something like this:
add_action( 'wp_footer', function () {
if ( ! is_page( array( 42, 'Page Name', 'about-us', 968 ) ) ) return;
// rest of snippet code here
} );
But it was not work, cause "unexpected if"
function custom_page() {
global $post;
if( $post->ID == 18) { ?>
<!-- do your stuff here -->
}
add_action( 'wp_footer', 'custom_page');

Get multiple post thumbnail image title or description in Wordpress

Got multiple featured images in a post and need the description of all or title of all in the loop.
Function to get description
/**
* Retrieve Post Thumbnail Description.
*
* #param string $post_type The post type.
* #param string $id The id used to register the thumbnail.
* #param int $post_id Post ID.
* #return string
*/
public static function the_post_thumbnail_description($post_type, $id, $post_id) {
$post_id = (NULL === $post_id) ? get_the_ID() : $post_id;
$postThumbnailID = get_post_meta($post_id, "{$post_type}_{$id}_thumbnail_id", true);
$description = get_post($postThumbnailID)->post_content;
echo $description;
}
Below is the statement to call this function
MultiPostThumbnails::the_post_thumbnail_description(get_post_type(), 'feature-image-'.$i.'', Null).'<br>';

Serialize translateble entity

For translate my entity product use next code
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
class Product
{
/**
* #Groups({"prod_translate"})
*/
use ORMBehaviors\Translatable\Translatable;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Groups({"prod"})
*/
private $id;
...
Translatable create new entity ProductTranslation with table in DB product_translation with id, translatable_id, locale and translatble properties.
Translation work perfectly. In page just write {{ product.translation.en/sp.name }}
When use ajax pagenation use serializer for return data.
Tried JMS\Serializer\SerializerBuilder and Symfony\Component\Serializer\Serializer
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Doctrine\Common\Annotations\AnnotationReader;
$products = $em->getRepository('AppBundle:Product')->findNextPageByBrandCategoryIds( array($cat), $brand, $offset, $limit );
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getID();
});
$serializer = new Serializer(array($normalizer));
$jsonObject = $serializer->normalize($products, 'json', array('groups' => array('prod', 'prod_translate')) );
Without groups serializet return "Maximum execution time 180second".
With groups return only Product data without translations.
What annotation or else manipulation must do for fix this issue? Please help!
Edit:
Tried Use next queries:
public function findNextPageByBrandCategoryIds(array $cat_ids, $brand_id, $offset=0, $limit=8 )
{
$qb = $this->createQueryBuilder('p');
if( !empty($cat_ids) ){
$cat_ids = implode(',', $cat_ids);
$qb->join('p.categories', 'c')
->where($qb->expr()->in('c.id', $cat_ids ) );
}
if( !empty($brand_id) ){
$qb->andWhere('p.brand = :brand')
->setParameter('brand', $brand_id);
}
if( $offset>0 ){
$qb->setFirstResult( $offset );
}
$qb->setMaxResults( $limit );
return $qb->getQuery()->getResult();
}
private function findNextPageByBrandCategoryIds($cat_id, $brand_id, $offset=0, $limit=8 )
{
$em = $this->getDoctrine()->getManager();
$sql = "SELECT p.id, t.id AS translate_id " .
"FROM product p INNER JOIN product_translation t ON t.translatable_id = p.id";
$where .= ' WHERE 1=1 ' ;
$rsm = new ResultSetMappingBuilder($em);
if( !empty($cat_id) ){
$sql .= " LEFT JOIN products_categories c ON c.product_id = p.id ";
$where .= " AND c.category_id = ".$cat_id;
}
if( !empty($brand_id) ){
$where .= " AND p.brand = ".$brand_id;
}
$limit = ' LIMIT '.$limit;
if( $offset>0 ){
$limit .= ' OFFSET '.$offset;
}
$sql = $sql.$where.$limit;
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Product', 'p');
$rsm->addJoinedEntityFromClassMetadata('AppBundle\Entity\ProductTranslation', 't', 'p', 'product', array('id' => 'translatable_id'));
$query = $em->createNativeQuery($sql, $rsm);
return $query->getResult();
}
Debug almost every line - they are right.
If use setHint(\Doctrine\ORM\Query::HINT_FORCE_PARTIAL_LOAD, true) - work but return products only, without translations.
The Maximum execution time 180 second message is an error that has nothing to do with annotations or the serializer.
In your php.ini you have a max_execution_time option to configure the limit of a script in seconds. You can also set it with the function set_time_limit($seconds)by code, but I would not recommend to use it.
Anyway, I would bet that you are doing a very large query. How many results are you limiting?
Nik fix this issue:
On Brand, Category and Product Entities
use JMS\Serializer\Annotation\MaxDepth;
/**
* #MaxDepth(1)
*/
private $products;
/**
* #MaxDepth(1)
*/
private $categories;
/**
* #MaxDepth(1)
*/
private $brand;

Fatal error: Call to a member function get_results() on a non-object

I am using revolution slider plugin . I am getting above error on one of my front end form. There is one file called db.class.php in that plugin where I am getting this error. Here is the code in that file..
<?php
class UniteDBRev{
private $wpdb;
private $lastRowID;
/**
*
* constructor - set database object
*/
public function __construct(){
global $wpdb;
$this->wpdb = $wpdb;
}
/**
*
* throw error
*/
private function throwError($message,$code=-1){
UniteFunctionsRev::throwError($message,$code);
}
//------------------------------------------------------------
// validate for errors
private function checkForErrors($prefix = ""){
if(mysql_error()){
$query = $this->wpdb->last_query;
$message = $this->wpdb->last_error;
if($prefix) $message = $prefix.' - <b>'.$message.'</b>';
if($query) $message .= '<br>---<br> Query: ' . $query;
$this->throwError($message);
}
}
/**
*
* insert variables to some table
*/
public function insert($table,$arrItems){
global $wpdb;
$this->wpdb->insert($table, $arrItems);
$this->checkForErrors("Insert query error");
$this->lastRowID = $wpdb->insert_id;
return($this->lastRowID);
}
/**
*
* get last insert id
*/
public function getLastInsertID(){
global $wpdb;
$this->lastRowID = $wpdb->insert_id;
return($this->lastRowID);
}
/**
*
* delete rows
*/
public function delete($table,$where){
UniteFunctionsRev::validateNotEmpty($table,"table name");
UniteFunctionsRev::validateNotEmpty($where,"where");
$query = "delete from $table where $where";
$this->wpdb->query($query);
$this->checkForErrors("Delete query error");
}
/**
*
* run some sql query
*/
public function runSql($query){
$this->wpdb->query($query);
$this->checkForErrors("Regular query error");
}
/**
*
* insert variables to some table
*/
public function update($table,$arrItems,$where){
$response = $this->wpdb->update($table, $arrItems, $where);
if($response === false)
UniteFunctionsRev::throwError("no update action taken!");
$this->checkForErrors("Update query error");
return($this->wpdb->num_rows);
}
/**
*
* get data array from the database
*
*/
public function fetch($tableName,$where="",$orderField="",$groupByField="",$sqlAddon=""){
global $wpdb;
$query = "select * from $tableName";
if($where) $query .= " where $where";
if($orderField) $query .= " order by $orderField";
if($groupByField) $query .= " group by $groupByField";
if($sqlAddon) $query .= " ".$sqlAddon;
$response = $this->wpdb->get_results($query,ARRAY_A);
$this->checkForErrors("fetch");
return($response);
}
/**
*
* fetch only one item. if not found - throw error
*/
public function
fetchSingle($tableName,$where="",$orderField="",$groupByField="",$sqlAddon=""){
$response = $this->fetch($tableName, $where, $orderField, $groupByField, $sqlAddon);
if(empty($response))
$this->throwError("Record not found");
$record = $response[0];
return($record);
}
/**
*
* escape data to avoid sql errors and injections.
*/
public function escape($string){
$string = esc_sql($string);
return($string);
}
}
?>
I am getting this error in fetch function. I have tried with global $wpdb. But no luck. I have loaded wp-load.php also but no luck.

Woocommerce call url (after complete order)

I have 3 questions (need help):
I do not know, how to run this plugin (gives me fatal error) please check my script (I am beginner)
Need help with admin page to set up APIkey and choose language for call url http://xxx.CZ or http://xxx.SK (This page is not scripted yet)
How to add my plugin admin page to woocommerce admin page?
This plugin is for Woocommerce. It is supposed to call specific URL (http://heureka.cz/or .sk/dotaznik/"Clients API set up in admin page in woocommerce"/"Customers email"/"Order ID"/"bought Products ID"/) when customers order si complete.
I am beginner in PHP and Wordpress. Thank you all for helping me.
CODE:
<?php
/*
Plugin Name: Overené zákazníkmi Heureka
Plugin URI: http://www.podujatie.eu
Version: 0.1
Description:
Author: Podujatie.eu, Ing. Igor Kóňa
Tested up to: 3.6
Author URI: http://www.podujatie.eu
Text Domain: woocommerce-new-badge
License: GNU General Public License v3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/**
* Check if WooCommerce is active
**/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
if ( ! class_exists( 'WC_HO' ) ) {
class WC_HO {
function heurekaovereno( $order_id ) {
error_log( "Order complete for order $order_id", 0 ); }
add_action( 'woocommerce_order_status_completed', 'heurekaovereno' );
// order object (optional but handy)
$order = new WC_Order( $order_id );
// do some stuff here
private function sendRequest($url)
{
$parsed = parse_url($url);
$fp = fsockopen($parsed['host'], 80, $errno, $errstr, 5);
if (!$fp) {
throw new HeurekaOverenoException($errstr . ' (' . $errno . ')');
} else {
$return = '';
$out = "GET " . $parsed['path'] . "?" . $parsed['query'] . " HTTP/1.1\r\n" .
"Host: " . $parsed['host'] . "\r\n" .
"Connection: Close\r\n\r\n";
fputs($fp, $out);
while (!feof($fp)) {
$return .= fgets($fp, 128);
}
fclose($fp);
$returnParsed = explode("\r\n\r\n", $return);
return empty($returnParsed[1]) ? '' : trim($returnParsed[1]);
}
}
/**
* Sends request to Heureka Overeno service and checks for valid response
*
* #return boolean true
*/
public function send()
{
if (empty($this->email)) {
throw new HeurekaOverenoException('Customer email address not set');
}
// create URL
$url = $this->getUrl() . '?id=' . $this->apiKey . '&email=' . urlencode($this->email);
foreach ($this->products as $product) {
$url .= '&produkt[]=' . urlencode($product);
}
foreach ($this->productsItemId as $itemId) {
$url .= '&itemId[]=' . urlencode($itemId);
}
// add order ID
if (isset($this->orderId)) {
$url .= '&orderid=' . urlencode($this->orderId);
}
// send request and check for valid response
$contents = $this->sendRequest($url);
if ($contents == FALSE) {
throw new HeurekaOverenoException('Unable to create HTTP request to Heureka Overeno service');
} elseif ($contents == self::RESPONSE_OK) {
return TRUE;
} else {
throw new HeurekaOverenoException($contents);
}
}
/**
* Adds ordered products using item ID
*
* #param string $itemId Ordered product item ID
*/
public function addProductItemId($itemId)
{
$this->productsItemId[] = $itemId;
}
/**
* Adds ordered products using name
*
* Products names should be provided in UTF-8 encoding. The service can handle
* WINDOWS-1250 and ISO-8859-2 if necessary
*
* #param string $productName Ordered product name
*/
public function addProduct($productName)
{
$this->products[] = $productName;
}
/**
* Heureka endpoint URL
*
* #var string
*/
const BASE_URL = 'http://www.heureka.cz/direct/dotaznik/objednavka.php';
const BASE_URL_SK = 'http://www.heureka.sk/direct/dotaznik/objednavka.php';
/**
* Language IDs
*
* #var int
*/
const LANGUAGE_CZ = 1;
const LANGUAGE_SK = 2;
/**
* Valid response value
*
* #var string
*/
const RESPONSE_OK = 'ok';
/**
* Shop API key
*
* #var string
*/
private $apiKey;
/**
* Customer email
*
* #var string
*/
private $email;
/**
* Ordered products
*
* #var array
*/
private $products = array();
/**
* Order ID
*
* #var int
*/
private $orderId;
/**
* Current language identifier
*
* #var int
*/
private $languageId = 1;
/**
* Ordered products provided using item ID
*
* #var array
*/
private $productsItemId = array();
/**
* Initialize Heureka Overeno service
*
* #param string $apiKey Shop API key
* #param int $languageId Language version settings
*/
public function __construct($apiKey, $languageId = self::LANGUAGE_CZ)
{
$this->setApiKey($apiKey);
$this->languageId = $languageId;
}
/**
* Sets API key and check well-formedness
*
* #param string $apiKey Shop api key
*/
public function setApiKey($apiKey)
{
if (preg_match('(^[0-9abcdef]{32}$)', $apiKey)) {
$this->apiKey = $apiKey;
} else {
throw new OverflowException('Api key ' . $apiKey . ' is invalid.');
}
}
/**
* Sets customer email
*
* #param string $email Customer email address
*/
public function setEmail($email)
{
$this->email = $email;
}
// Default options
add_option( 'wc_nb_newness', '30' );
// Admin
add_action( 'woocommerce_settings_image_options_after', array( $this, 'admin_settings' ), 20);
add_action( 'woocommerce_update_options_catalog', array( $this, 'save_admin_settings' ) );
/*-----------------------------------------------------------------------------------*/
/* Class Functions */
/*-----------------------------------------------------------------------------------*/
// Load the settings
function admin_settings() {
woocommerce_admin_fields( $this->settings );
}
// Save the settings
function save_admin_settings() {
woocommerce_update_options( $this->settings );
}
if (!isset($wpdb)) $wpdb = $GLOBALS['wpdb'];
$heurekaovereno_ver = '1.00';
$WC_HO = new WC_HO();
}
}
}
?>
This script works (it has few bugs, but it works) only when you put it in functions.php
Here is where I am asking, why is it.

Resources