Get multiple post thumbnail image title or description in Wordpress - 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>';

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

How to get user activation URL in wordpress?

for the following code:
add_action( 'user_register', 'my_user_register', 10, 1 );
function my_user_register($user_id){
// how do i get user activation url
// todo: send user an activation email
}
I want to send an activation email to user, but I don't know how to get the activation url. Please advice.
you can send email activation link like this.
global $theme_settings;
$hidDiv="none";
$login_page_url = get_permalink($theme_settings['userlogin_page']);
$home_url = get_option('siteurl');;
$firstname = sanitize_text_field($_POST['firstname']);
$username = sanitize_text_field($_POST['email']);
$password = sanitize_text_field($_POST['password']);
$email = sanitize_text_field($_POST['email']);
$lastname = $_POST['lastname'];
$company = $_POST['company'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$mailemail = $_POST['mailingaddress'];
$user_id = wp_create_user( $username, $password, $email );
if ( is_wp_error( $user_id ) ) {
$error_string = $user_id->get_error_message();
}else
{
theme_user_register($user_id);
$thanks_msg_page_url = get_permalink($theme_settings['userthanks_page']);
$trackcode = get_user_meta($user_id, 'p_user_registration_code', true);
$site_name = get_option('blogname');
$track_url = get_option('siteurl').'/confirmation?trackid='.$user_id.'&trackcode='.$trackcode;
$headers = "MIME-Version: 1.0";
$headers .= "Content-Type: text/html; charset=UTF-8";
$headers .= "From: $site_name < $from >" . "\r\n";
$message = "<p> Hello ".$username;
$message.="<p>Thank you for registering with us. Please click on the below link or copy and paste to the browser to activate your account.</p>";
$message.="<p> $track_url</p><br>Best Regards,<br>Support Team";// Need to change this
$from = get_option('admin_email');
$site_name = get_option('blogname');
wp_mail($email, 'Registration Confirmation', $message, $headers,'');
$thanks_msg_page_url = get_permalink(theme_settings['userthanks_page']);
wp_redirect($thanks_msg_page_url);
exit;
}
I am not sure if I understand why you want to get activation URL through coding, unless of course if you want to customize the default new user notification email sent by WordPress.
If you simply want to customize the Notification Email sent to the New User upon successful User Registration then you should use Filters wp_new_user_notification_email - customise email sent to User and/or wp_new_user_notification_email_admin - customise email sent to Admin.
Both these functions are in "wp-includes/pluggable.php". The filter definitions are as follows...
/**
* Filters the contents of the new user notification email sent to the site admin.
*
* #since 4.9.0
*
* #param array $wp_new_user_notification_email {
* Used to build wp_mail().
*
* #type string $to The intended recipient - site admin email address.
* #type string $subject The subject of the email.
* #type string $message The body of the email.
* #type string $headers The headers of the email.
* }
* #param WP_User $user User object for new user.
* #param string $blogname The site title.
*/
$wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname );
... and ...
/**
* Filters the contents of the new user notification email sent to the new user.
*
* #since 4.9.0
*
* #param array $wp_new_user_notification_email {
* Used to build wp_mail().
*
* #type string $to The intended recipient - New user email address.
* #type string $subject The subject of the email.
* #type string $message The body of the email.
* #type string $headers The headers of the email.
* }
* #param WP_User $user User object for new user.
* #param string $blogname The site title.
*/
$wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname );
The typical filter function code block looks like this...
function custom_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {
$wp_new_user_notification_email['subject'] = 'Your Subject';
$wp_new_user_notification_email['message'] = 'Your Email Message';
return $wp_new_user_notification_email;
}
Inside the add_filter functions for these filters, you can get the User specific information using the $user passed to the filter function, like...
$user_name = $user->user_login;
$user_email = $user->user_email;
Using the $user object, you can get the User information and build your own activation link.
Again, I am not sure if I've followed the motive behind this question correctly; but this is the path I will follow if I'm at this sort of stuff to implement.

Symfony Doctrine : get field value in foreach loop on fetchAll()

I'm trying to display some fields of a table 'Post' using a raw query :
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT * FROM Post WHERE category_id = 1");
$statement->execute();
$posts = $statement->fetchAll();
...
foreach($posts as $post) {
$xml .= $post->getId();
$xml .= $post->getTitle();
$xml .= $post->getContent();
}
I've got an error "FatalErrorException: Error: Call to a member function getId() on a non-object in ..."
All those getters are right in my Post entity. Any suggestion about what I'm doing wrong ?
[EDIT]
$em = $this->getDoctrine()->getManager();
$post_repository = $em->getRepository('MyBundle:Post');
$posts = $post_repository->findBy(array('category_id' => 1));
foreach($posts as $post) {
$xml .= $post->getTitle();
}
Returns me "Unrecognized field: category_id".
My Post class :
class Post
{
/**
* #ORM\ManyToOne(targetEntity="MyBundle\Entity\Category", inversedBy="post")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* Set category
*
#param MyBundle\Entity\Category $category
*/
public function setCategory(\MyBundle\Entity\Category $category)
{
$this->category = $category;
}
/**
* Get category
*
#return MyBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
....
Why using directly your connection here? You should consider using the entity repository for your "posts" class. For example :
$posts = $em->getRepository('YourBundle:Post')->findBy(array('category_id' => 1));
this should work, just replace the YourBundle:Post with the proper bundle and class names. Same for the category_id, I can't guess without your implementation if it's the class property or the mapping name.
I suggest you to read more on the official Doctrine documentation to improve your knowledge on the subject.
When you execute a raw query using Doctrine's DBAL layer the results come back as an array of field names mapped to values rather than as entities.
Therefore you need something like this:
foreach($posts as $post) {
$xml .= $post['id'];
$xml .= $post['title'];
$xml .= $post['content';
}

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.

Wordpress - GD Star Rating - Set Rating after wp_insert_post

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;
}

Resources