How to implement Polylang functions in my theme's php file? - php

I am translating a site with Polylang that was created by someone else using a custom theme. Some strings couldn't be found by Polylang, so I need to manually register them for Polylang to see. Now, some of the strings were pretty easy to translate using __():
$args = shortcode_atts([
'link' => 'service',
'text' => __('Get the code now!'),
'title' => __('Code'),
'id' => '',
'class' => 'width300',
], $args, '' );
But I don't know how to translate strings in these scenarios:
$popup = do_shortcode('[popup id="110" link="vacancy" class="" title="Code" text="Get the code now!!" ]');
Or here words Details, Close
$script = '
<script>
$(document).ready(function(){
btn = $(\'.add_vakan_info\'),
popup = $(\'.add_popup\');
btn.click(function(){
var block_info = $(this).closest(\'.vacancy\').find(\'.content\');
if(block_info.hasClass(\'active\')){
block_info.removeClass(\'active\');
$(this).html(\'Details <i class="las la-angle-down"></i>\');
}else{
block_info.addClass(\'active\');
$(this).html(\'Close <i class="las la-angle-up"></i>\');
}
})
popup.click(function(){
var text = $(this).closest(\'.vacancy\').find(\'.title\').text(),
form = $(\'.vacancy_name\');
form.val(text);
})
FileInput();
})
</script>';
Or
else:
$html = '<h4>No vacancy </h4>';
Or
<div class="content col">
<div class="sp-20"></div>
<h4>Description</h4>
'.$description.'
<div class="sp-20"></div>
<h4>Requirements</h4>
'.$requirements.'
<div class="sp-20"></div>
<h4>Conditions</h4>
'.$conditions.'

You need to use Polylang's string translations API.
Step 1. Registering your strings.
// functions.php
add_action('init', function () {
$strings = array(
'no-vacancy' => 'No vacancy',
// Add more strings here...
);
foreach ($strings as $key => $string) {
pll_register_string('theme-' . $key, $string, 'Hardcoded Theme Strings');
}
});
Now these strings will appear in Languages > String translations menu, under the dropdown for Hardcoded Theme Strings
Step 2. Translate the Strings
else:
$html = '<h4>' . pll_e( 'No vacancy' ) . '</h4>';
The value you enter on the back-end in the string translations menu will be used when translating this value.

Related

Dynamic ID with JQUERY functions

I have a problem with my JQUERY code. Here's the code:
$maxcounter = $( '.testimonio-popup[id^="popup-"]' ).length;
var i = 0;
while (i < $maxcounter) {
$('#open-'+i).on('click', function() {
$('#popup-'+i).fadeIn('slow');
$('.testimonio-overlay').fadeIn('slow');
$('.testimonio-overlay').height($(window).height());
return false;
});
$('#close-'+i).on('click', function(){
$('#popup-'+i).fadeOut('slow');
$('.testimonio-overlay').fadeOut('slow');
return false;
});
i++;
}
It takes correctly the total of times the .testimonio-popup div is appearing in the site, and the fadeIn action for .testimoniooverlay class works.
But the fadeIn action for #popup-[number] is not working. Any help why?
For further assistance, I attach the PHP code that makes the query:
function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
add_shortcode( 'testimonios', 'display_testimonios' );
function display_testimonios($atts){
$atributos = shortcode_atts([ 'grupo' => 'PORDEFECTO', ], $atts);
$buffer = '<div class="testimonio-overlay"></div> ';
$contadorid = 0;
$q = new WP_Query(array(
'post_type' => 'test',
'tax_query' => array(
array(
'taxonomy' => 'grupos_testimonios',
'field' => 'slug',
'terms' => $atributos['grupo']
//'terms' => 'grupo-1'
)
)
) );
while ($q->have_posts()) {
$q->the_post();
$buffer .= '<div class="testimonio">';
$buffer .= '<div class="testimonio-img">' . get_the_post_thumbnail($_post->ID).'</div>';
$buffer .= '<div class="testimonio-titulo"><p>' . get_the_title() .'</p></div>';
$buffer .= '<div class="testimonio-intro"><div class="testimonio-parrafo">' . get_the_excerpt() . '</div><button class="testimonio-boton" id="open-'.$contadorid.'">Leer más</button></div></div>';
$buffer .= '<div class="testimonio-popup" id="popup-'.$contadorid.'"><div class="testimonio-popup-contenido"><div class="testimonio-cerrar"><button class="testimonio-boton-cerrar" id="close-'.$contadorid.'">x</button></div>';
$buffer .= '<div class="testimonio-popup-titulo"><p>' . get_the_title() .'</p></div>';
$buffer .= '<div class="testimonio-popup-contenido">' . get_the_content_with_formatting() . '</div></div></div>';
$contadorid = $contadorid + 1;
}
wp_reset_postdata();
return $buffer;
}
Thank you!
Frede
#Rory McCrossan is right (see comment).
I'm not sure what goes wrong there, but I would suggest you change this logic:
$("#open-1").on(....);
$("#open-2").on(....);
$("#open-3").on(....);
$("#close-1").on(....);
$("#close-2").on(....);
$("#close-3").on(....);
$("#popup-1").fadeIn()
$("#popup-2").fadeIn()
to using classes and attributes:
$(".popup-handler").on(.. check if open/close -> then action..);
$(".popup").filter(.. check for specific reference..).fadeIn()
And if you want to interact elements with different classes, add data attributes to them so you can find them when needed. Here is a simple example:
<!-- popup nr 1 -->
<div class="popup-handler" data-rel="1" data-action="open"></div>
<div class="popup" data-rel="1">
<div class="popup-handler" data-rel="1" data-action="close"></div>
</div>
<!-- popup nr 2 -->
<div class="popup-handler" data-rel="2" data-action="open"></div>
<div class="popup" data-rel="2">
<div class="popup-handler" data-rel="2" data-action="close">x</div>
</div>
<!-- jQuery -->
$(".popup-handler").on("click", function() {
/* get popup reference & action */
var rel = $(this).data("rel"),
action = $(this).data("action");
/* find the target popup */
var $popup = $(".popup").filter("[data-rel=" + rel + "]");
if (action == "open") {
$popup.fadeIn("slow");
/* ... other code when opening a popup... */
}
if (action == "close") {
$popup.fadeOut("slow");
/* ... other code when closing a popup... */
}
});
Demo here - 4 popups, working: jsfiddle
(Defining the same functions inside a while loop is generally a bad idea.)

Shopping Cart Issue in Codeigniter

I am trying to create a shopping cart in CodeIgniter, I tried the method mentioned in the documentation and it works perfectly. But when I try to use it in the templetes it did not works. In the documentation, the products are hard coded but I am fetching the products from a database and inserting it using ajax.
My Insert code JS
$(document).ready(function(){
$('.add-to-cart').click(function(){
var product_id=$(this).data("productid");
var product_name=$(this).data("productname");
var product_price=$(this).data("productprice");
var quantity=$('#' + product_id).val();
if(quantity !='' && quantity>0)
{
$.ajax({
url:"<?php echo base_url();?>Cart/insert_product",
method:"POST",
data:{
product_id:product_id,product_name:product_name,product_price:product_price,quantity:quantity
},
success:function(data)
{
alert("Product added into cart");
// alert("Product added into cart and product info is: ID:" + product_id +'\n\r name:' + product_name + '\n\r price:' + product_price + '\n\r quantity:' + quantity);
// $('#' + product_id).val('');
}
});
}
else
{
alert("Please enter quantity");
}
});
});
I test it using the alert to make sure that product is picking when I click "Add To Cart" Button.
My Controller Insert_Product
// my cart
public function insert_product()
{
$data=array(
'id' => $_POST['product_id'],
'qty' => $_POST['quantity'],
'price' => $_POST['product_price'],
'name' => $_POST['product_name']
);
// Inesrting Items into Cart
$this->cart->insert($data);
}
When I click on "Add To Cart" Button it shows me the success message, but I am pretty sure that the product is not inserting into the cart...
Place Where I am trying to access the product.
<!-- cart items -->
<div class="nav-cart-items">
<?php $i = 1;
if(!$this->cart->contents()){echo "no items found in cart";}
foreach ($this->cart->contents() as $items):
var_dump($items);
if(empty($items)){echo "cart is empty";}else{ echo "<h1>cart has data</h1>";?>
<div class="nav-cart-item clearfix">
<h4>Cart Details</h4>
<div class="nav-cart-img">
<a href="#">
<img src="cart_small_1.jpg" alt="">
</a>
</div>
<div class="nav-cart-title">
<a href="#">
<?php echo $items['name'];?>
</a>
<div class="nav-cart-price">
<span><?php echo $items['qty'];?> x</span>
<span><?php echo $this->cart->format_number($items['price']);?></span>
</div>
</div>
<div class="nav-cart-remove">
<i class="ui-close"></i>
</div>
</div>
<?php $i++; ?>
<?php } endforeach;?>
</div> <!-- end cart items -->
I am echoing the message "no items found in cart" if there are no items in the cart, and it shows me that. I also try this code
<?php
ob_start();
var_dump($this->cart->contents());
$result = ob_get_contents();
?>
to test the contents and it shows me the output :
F:\xampp\htdocs\cart\application\views\single_item.php:3:
array (size=0)
empty
As for I think that I am doing something wrong, but don't know where...
Please also suggest a cart solution in CodeIgniter, as in the documentation the Cart library is depreciated.
Any help regarding this will be highly appreciated.
PHP scripts, namely: <?php echo base_url();?> will not execute in .js files. Hence how in the comments your url is showing up in dev tools verbatim.
You could move the contents of the js file to your header template so it resides in a view. Or you could just define the base_url() yourself in js as a var (var base_url = 'http://somesite.com/';) and use it like base_url or do something like:
url:"/cart/insert_product" assuming that cart is not in a subdir of controllers
Why do you used $data in Controller.
If i am not wrong then you are sending values separately , not in " $data multiassociative array "
$data=array(
array(
'id' => $_POST['product_id'],
'qty' => $_POST['quantity'],
'price' => $_POST['product_price'],
'name' => $_POST['product_name'])
);
try to remove $data=array() and used following code:
$id = $this->input->post('product_id');
$quantity = $this->input->post('quantity');
$product_price = $this->input->post('product_price');
$product_name = $this->input->post('product_name');
I usually get the post data and insert into the table in this way:
$productId = $this->security->xss_clean($this->input->post('product_id'));
$quantity = $this->security->xss_clean($this->input->post('quantity'));
$productPrice = $this->security->xss_clean($this->input->post('product_price'));
$productName = $this->security->xss_clean($this->input->post('product_name'));
$data = array(
"id" => $productId,
"qty" => $quantity,
"price" => $productPrice,
"name" => $productName
);
$this->cart->insert($data);

Using Shortcode to Query Custom Post Type and Return Carousel

I am using wordpress and would like to offer the user the capability to use a shortcode to pull a slider into the post / page.
i.e [slider id="2"]
I have done the following:
Created custom post type 'Sliders'
Used Advanced Custom Fields to create all the fields required within the post type.
Created the shortcode using:
function landwSliderShortcode($atts = [], $content = null, $tag = '')
{
$atts = array_change_key_case((array)$atts, CASE_LOWER);
$slider_atts = shortcode_atts([
'id' => '1',
], $atts, $tag);
return $slider_atts['id'];
}
function landwSliderShortcodes_init()
{
add_shortcode('slider', 'landwSliderShortcode');
}
add_action('init', 'landwSliderShortcodes_init');
I now need to call another function that is going to perform the WP_Query of the custom post type and build the HTML slider... It is this part I am struggling with. I have got this far:
function getSliderData($sliderId) {
$slidercount = 0;
$args = array(
'post_type' => 'slider',
'post_status' => 'publish',
'posts_per_page' => '1',
'p' => $sliderId,
);
$sliderLoop = new WP_Query( $args );
if ( $sliderLoop->have_posts() ) :
while ( $sliderLoop->have_posts() ) : $sliderLoop->the_post();
$image = get_sub_field('image');
$image_render = $image['sizes'][$image_asset_size];
$add_link = get_sub_field('add_link');
$link_type = get_sub_field('link_type');
$internal_link = get_sub_field('internal_link');
$external_link = get_sub_field('external_link');
$add_lightbox = get_sub_field('add_lightbox');
$lightboxasset = get_sub_field('lightbox_asset');
$lightboxassetcaption = get_sub_field('lightbox_caption');
$caption = get_sub_field('caption');
$sub_caption = get_sub_field('sub_caption');
?>
<div class="slider-wrap">
<?php if ($add_link) {
if ($link_type == "External") {
echo '<a class="carousel-slide-link" href="'.$external_link.'" target="_blank"></a>';
} else {
echo '<a class="carousel-slide-link" href="'.$internal_link.'"></a>';
}
}
?>
<?php if ($add_lightbox) { ?>
<a class="carousel-slide-link" data-fancybox data-src="#SliderModal<?php echo $slidercount ?>" target="_blank" href="javascript:;"></a>
<?php } ?>
<img src="<?php echo $image_render; ?>">
<!-- 6 Mar 17 added conditional to show the caption -->
<?php if (strlen($sub_caption) > 0 || strlen($caption) > 0) : ?>
<div class="post-wrap-meta">
<span><?php echo $sub_caption; ?></span>
<p class="slider-caption-text"><?php echo $caption; ?></p>
</div>
<?php endif ?>
</div>
<!-- output the modal -->
<div style="display: none;" class="standard__modal" id="SliderModal<?php echo $slidercount; ?>">
<?php echo $lightboxasset ?>
<p class="slider-caption-text">
<?php echo $lightboxassetcaption ?>
</p>
</div>
<?php
$slidercount ++;
endwhile;
?>
<?php
endwhile;
wp_reset_postdata();
endif;
}
I hope to be able to pass the sliderId var to this function and return a fully functioning slider (there is a small Javascript function I need to add to this HTML as well).
Many thanks in advance to anyone whole can help with this.
Instead of using WP_Query, ->have_posts(), while, wp_reset_postdata, use a simple get_posts($args) and do a for loop over the results.
- - see When should you use WP_Query vs query_posts() vs get_posts()?
And instead of echo, build a HTML string that will be returned to the shortcode. WordPress shortcodes should never echo anything, they expect a string to be returned. PHP heredoc is perfect for that, example:
function getSliderData($sliderId) {
$some_var = 'Value of the var';
$html = <<<HTML
<div>$some_var</div>
<h3>$post->title</h3>
HTML;
return $html;
}
Important: the closing HTML; must not have white spaces before or after.
Ideally, you'll build the $html bit by bit, making sure it's returning the perfect markup. You can use $html .= to compose the string in more than one operation.

reload just a part of a page after ajax request

I am trying to add a search module for my data listing .
my function that i post the request to, renders a view.
how can i load the list grid after pushing search button?
should i echo a html code, or render a view and write that view in that position?
I am totally confused ...
public function actionSell() {
$cond="";
if($_POST) {
foreach ($_POST as $key => $value) {
$_POST[$key] = str_replace(',', '', stripslashes(mysql_real_escape_string($value)));
}
$melk_id = $_POST['melk_id'];
$city_id = $_POST['city_id'];
$cost_from = $_POST['cost_from'];
$cost_to = $_POST['cost_to'];
$metraj_from = $_POST['metraj_from'];
$metraj_to = $_POST['metraj_to'];
if($melk_id) $cond .= ' and melk_id='.$melk_id;
if($city_id) $cond .= ' and city_id='.$city_id;
if($cost_from) $cond .= ' and cost >='.$cost_from;
if($cost_to) $cond .= ' and cost <='.$cost_to;
if($metraj_from) $cond .= ' and metraj >='.$metraj_from;
if($metraj_to) $cond .= ' and metraj <='.$metraj_to;
}
$dataProvider = new CActiveDataProvider('Data', array('criteria' => array(
'condition' => 'type = 0 '.$cond,
'order' => 'id DESC',
),
'pagination' => array('pageSize' => 15)
));
$this->render('sell', array(
'dataProvider' => $dataProvider,
));
}
I'm not a php developer but I'll try yo answer in a jQuery manner.
Suppose you hold your list grid in a container: <div id="container"> //the grid </div>
You fill the container from a View that holds the grid
You have Seach TextBox
<input id="searchBox" type="text" name="SeachTxt" Value="Some text"/>
And a Button :
<input id="SearchBtn" type="button" value="Search Now!">
Next you must have a jQuery ajax post function, like this one:
jQuery("#SearchBtn").click(function(e) {
e.preventDefault();
jQuery.ajax({
url: 'index.php?searchString=' + jQuery("#searchBox").val(),
success: function(result) {
jQuery("#container").html(result);
}
});
});
you could use renderPartial, like
$this->renderPartial('_ajaxContent', array(
'dataProvider' => $dataProvider
), false, true
);

Problems with an accordion menu using jquery and PHP to show 'active' links and keep menu slider open on current page

With my very little knowledge of jQuery and PHP, I have almost accomplished an accordion menu where the links display as 'active' when the active page is open, and the slider menu stays open on the correct section when on the active page.
I have added some php to the bottom links. The child links display as active when on the active page. However the parent element does not, and also closes itself.
I'd really appreciate any help!!!
Here's my code as it stands:
<ul id="accordion">
<ul class="parent">
<li>
CMS
<ul class="child">
<li>Intro to CMS</li>
<li>Specific CMS</li>
<li>Installing a CMS</li>
</ul>
</li>
</ul>
<ul class="parent">
<li>
<?php
if ($this_page=="Customising-Google-Forms" || $this_page=="Web-Event-Notes"){
echo "Other";
}else{
echo "Other";
}
?>
<ul class="child">
<?php
if ($this_page=="Customising-Google-Forms"){
echo "<li class=\"current\">Customising-google-forms</li>";
}else{
echo "<li>Customising Google Forms</li>";
}
?>
<?php
if ($this_page=="Web-Event-Notes"){
echo "<li class=\"current\">Web Event Notes</li>";
}else{
echo "<li>Web-Event-Notes</li>";
}
?>
</ul>
</li>
</ul>
<script type="text/javascript">
$(function(){
// hide all links on load
$('ul.child').hide();
// for image
// $("a.slide:first").css("background-image","url('path')");
$('ul.parent a.slide').click(function(){
$('ul.parent a.slide').css("color","#000");
$('ul.parent a.slide').hover(function(){
$(this).css("color","#ef492f");
});
$('ul.parent a.slide').mouseout(function(){
$(this).css("color","#000");
});
$(this).mouseout(function(){
$(this).css("color","#000");
});
$(this).css("color","#000");
// slide all up
$('ul.child').slideUp('slow');
// show the links of current heading
$(this).next().find('a').show();
// slide down current heading
$(this).next().slideDown('fast');
// prevent default action
return false;
});
if($("ul li a").hasClass("current")) {
$(this).closest("ul").slideDown("fast") //open the menu
}
});
</script>
In my opinion the best way to accomplish this is by making a PHP array that contains the links and then build a html menu out of it. In this way PHP can control which of the links will hold the 'current' class based on the url parameters. The last step will be jquery to just grab the '.current' listitem and make it visible. The below may seem like a lot of work, but when you get it, it will be powerful and reusable :)
//Grab the page parameter somehow.. below = example
$page = $_GET['page'];
//Build menu array containing links and subs
$items = Array(
//highest level
'cms' => Array(
'title' => 'CMS',
//Array containing submenu items for cms
'subs' => Array(
'intro-to-cms' => Array('title' => 'Intro to CMS'),
'specific-cms' => Array('title' => 'Specific CMS'),
'installing-a-cms' => Array('title' => 'Installing a CMS')
),
)
);
//Display the menu
echo navlinks($items, $page);
/**
* Recursive function creates a navigation out of an array
* #param type $items
* #return string containing navigationlist
*/
function navlinks($items, $page=false)
{
$html = '<ul>';
foreach ($items AS $uri => $info) {
//Check if the pagename is the same as the link name and set it to current when it is
$html .= '<li'.($info['title'] == $page ? ' class="current"' : '').'>';
echo ' ' . $info['title'] . '';
//If the link has a sub array, recurse this function to build another list in this listitem
if (isset($info['subs']) && is_array($info['subs'])) {
$html .= navlinks($info['subs']);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}

Categories