I need to count all records in a single table, so ..In my action
public function executeTesting(sfWebrequest $r)
{
$this->applicants = Doctrine_core::getTable('Applicants')->count();
$this->setLayout(false);
}
and I can display the records in a template
testingSucess.php
<?php echo $applicants ?>//returns number of records example 890
But I want it to display in another templates.Let say I want to 'embed' to another template(failureSuccess.php).Any suggestions?
You may consider using an AJAX call, and making a little change at your code you can avoid the template.
So let's change your action to this:
class miscActions extends sfActions
{
public function executeTotal(sfWebRequest $request)
{
$total = Doctrine::getTable('Utenti')->findAll()->count();
return $this->renderText(json_encode(array('total' => $total)));
}
}
And now you can retrieve that value in a template with, for example, jQuery:
<script type="text/javascript">
$.ajax({
url: '<?php echo url_for("misc/total") ?>',
dataType: 'json',
success: function(data){
console.log(JSON.stringify(data));
console.log("Total: " + data.total);
// And if you want to update a div content
$("#responsecontainer").html(data.total);
}
});
</script>
Got it..Just remove the action and create a helper instead,so in my lib/helper/TotalHelper.php
<?php
function getTotal() {
$applicants = Doctrine_core::getTable('Applicants')->count();
return $applicants;
}
and in template (failureSuccess.php)
<?php use_helper('Total') ?>
<?php echo getTotal() ?>
So convenient..
Related
A newbie here...I am trying to apply a system that allows readers to "infinitely" scroll down to the next posts after finishing a single post so that they don't have to manually click them.
(Like this website does:
https://dancingastronaut.com/2020/12/maceo-plex-confronts-racism-and-diversity-in-latest-single-cinemax/)
I tried the “auto load next post” plugin, but it didn’t work on my theme :(.
I’m currently using the Amphibious theme developed by templatepocket.
https://wordpress.org/themes/amphibious/
This is the biggest part I’m having a struggle with, and I think my website is good to go once it’s applied. I hope someone can help me out here!
Thanks!
You would first need to edit your single post template, usually single.php, and add a trigger when a user scrolls past that point.
<?php $gpNextPost = get_next_post(); ?>
<div class="gp-infinite-scroll" style="display: none;"><?php echo $gpNextPost->ID; ?></div>
Then call an AJAX function to load next post's content and also replace the URL in the browser's address bar.
Here's a rough example:
function gp_infinite_scroll($pid){
if (is_single()) { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$(window).scroll(function() {
var footerPos = $('footer').last().position().top;
var pos = $(window).scrollTop();
if (pos+(screen.height*4) > footerPos) {
if ($(".gp-infinite-scroll").first().hasClass('working')) {
return false;
} else {
$(".gp-infinite-scroll").first().addClass('working');
}
var gpNextPostId = $(".gp-infinite-scroll").first().text();
var data = {
'action': 'gp_is',
'gpNextPostId': gpNextPostId
};
$.post(ajaxurl, data, function(response) {
$(".gp-infinite-scroll").first().replaceWith(response);
}, 'html');
}
// Update new URL
var currUrl = $(".gp-post-header").first().attr("url");
var currTitle = $(".gp-post-header").first().attr("title");
if ($(".gp-post-header").length > 1 && history.pushState) {
for (var i=0; i<$(".gp-post-header").length; i++) {
var trigger = $(".gp-post-header").eq(i).next().position().top;
if (pos+(screen.height/2) >= trigger) {
currUrl = $(".gp-post-header").eq(i).attr("url");
currTitle = $(".gp-post-header").eq(i).attr("title");
}
}
}
if (location.href != currUrl) {
history.pushState({}, currTitle, currUrl);
}
});
});
</script>
<?php }
}
add_action( 'wp_head', 'gp_infinite_scroll' );
function gp_infinite_scroll_callback() {
if (isset($_POST['gpNextPostId']) && $_POST['gpNextPostId']) {
$the_query = new WP_Query(array('p'=>$_POST['gpNextPostId']));
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
// Change to your own Single Post template file
get_template_part( 'template-parts/content', 'single' );
}
}
wp_reset_postdata();
}
wp_die();
}
add_action( 'wp_ajax_gp_is', 'gp_infinite_scroll_callback' );
add_action( 'wp_ajax_nopriv_gp_is', 'gp_infinite_scroll_callback' );
This code is untested but it should get you going. If the above seems too much for you then you migh try some of the related plugins.
Is there a way of adding Javascript to a page directly but having Wordpress to wait for jQuery to load? Just as with using wp_enqueue_script?
In the custom page template I have the following code:
<?php if (isset($_GET['status']) && $_GET['status'] == 'newly_created') : ?>
<script>
$(function() {
App.dialogs.afterPetitionCreate();
});
</script>
<?php endif; ?>
Wordpress barks that $ is undefined. Now I do not want to load a entire .js file just to call that function. So in that sense wp_enqueue_script isn't an option. I only want to fire some JavaScript directly on the page but I do want to wait for jQuery to load.
This is what I also tried, adding the JavaScript to the footer with Wordpress:
<?php if (isset($_GET['status']) && $_GET['status'] == 'newly_created') :
add_action('wp_footer', 'my_footer_scripts');
function my_footer_scripts() { ?>
<script>
$(function () {
App.dialogs.afterPetitionCreate();
});
</script>
<?php } ?>
<?php endif; ?>
But unfortunately the same error appears $ is undefined.
So what would be the correct way to quickly load some Javascript on a custom Wordpress page template AND wait for jQuery to load?
I do not think this is a good practice.
It is better to change logic to something like this:
<?php if (isset($_GET['status']) && $_GET['status'] == 'newly_created') : ?>
<input type='hidden' id='status' name='status' value='newly_created'>
<?php endif; ?>
script.js:
$(function() {
if ( $('#status').val() === 'newly_created' ) {
App.dialogs.afterPetitionCreate()
}
});
and
wp_enqueue_script( 'afterPetitionCreate', '/path/to/script.js', array( 'jquery' ), '', true );
p.s. you can wrap wp_enqueue_script() into is_page_template( 'my-cool-page-teplate.php' ).
Have you tried running the script within the document ready event like the following code below?
<script>
jQuery(document).ready(function($){
$(function () {
App.dialogs.afterPetitionCreate();
});
});
</script>
The .ready event occurs when the object of the document or the DOM is loaded which makes it perfect to place all of your jquery events and other functions.
This is the code I ended up writing, and does exactly what I want. Like Submit Parkash mentioned, jQuery needs to be used instead of $.
/*
* Adds a single bit of Javascript to the page.
*/
function theme_embed_script($script) {
add_action('wp_footer', function ($script) {
echo '<script type="text/javascript">' . $script . '</script>';
}, 10);
do_action('wp_footer', $script);
}
Usage:
<?php theme_embed_script('jQuery(function () { alert("Hello"); });'); ?>
OR use Wordpress' wp_add_inline_script() script like David mentioned.
How can I display "Sold Individually" field in my custom product type "Test Product"?
I tried with the following hook function
static function addField() {
echo "<script>jQuery('.show_if_simple').addClass('show_if_test');
jQuery('._sold_individually_field.show_if_simple').addClass('show_if_test');
</script>";
}
add_action('woocommerce_product_options_general_product_data','addField'));
Please add below code in your function.php file. you need to add class show_if_{your_custom_product_type} in your case it will be show_if_test. replace show_if_simple_rental with show_if_{your_custom_product_type}. for more information click here
function wh_simple_rental_admin_custom_js() {
if ('product' != get_post_type()) :
return;
endif;
?>
<script type='text/javascript'>
jQuery(document).ready(function () {
//for Inventory tab
jQuery('.inventory_options').addClass('show_if_simple_rental').show();
jQuery('#inventory_product_data ._sold_individually_field').parent().addClass('show_if_simple_rental').show();
jQuery('#inventory_product_data ._sold_individually_field').addClass('show_if_simple_rental').show();
});
</script>
<?php
}
add_action('admin_footer', 'wh_simple_rental_admin_custom_js');
I use this script to filter posts from single category. I based on tags which generate also a class. It is possible to generate this script by WordPress with all tags from my site?
For example below 2 scripts (now I have 12 scripts of this type):
$(document).ready(function(){
$('tr').show();
$("#aipa").click(function(){
$("tr").show();
$('tr:not(:first)').not(".aipa").slideToggle('fast');
});
});
$(document).ready(function(){
$('tr').show();
$("#ris").click(function(){
$("tr").show();
$('tr:not(:first)').not(".ris").slideToggle('fast');
});
});
Now when I add new tags I must manually add another script:
$(document).ready(function(){
$('tr').show();
$("#next-tag").click(function(){
$("tr").show();
$('tr:not(:first)').not("#next-tag").slideToggle('fast');
});
});
Here's a way to do this. This assumes that you're using the standard blog tag system, and that your variable you're using as your ID and class is the tag's slug. Alter it as needed for your needs.
<?php $tags = get_tags(); ?>
<script>
$(document).ready(function(){
<?php foreach ( $tags as $tag ) { ?>
$('tr').show();
$("#<?php echo $tag->slug; ?>").click(function(){
$("tr").show();
$('tr:not(:first)').not(".<?php echo $tag->slug; ?>").slideToggle('fast');
});
<?php } ?>
});
</script>
This will create a single document ready function, and then generate multiple click functions.
Are currently developing a plugin that need ajax. Was thinking of doing it "correctly", so am trying to use admin-ajax.php. However I always get 0 as response, and somehow get the feeling that it never gets to my callback.
Here's the code, have tried to keep simple.
Load js and setting admin-ajax.php outside admin
wp_enqueue_script('my-more-posts-ajax', SE_WP_MY_PLUGIN_URI . '/js/more-posts-ajax.js?' . rand(), array('jquery'));
wp_localize_script('my-more-posts-ajax', 'MyAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
Actions for callback
add_action('wp_ajax_nopriv_my_more_posts', array($this, 'load_more_posts_callback'));
add_action('wp_ajax_my_more_posts', array($this, 'load_more_posts_callback'));
PHP callback function
public function load_more_posts_callback() {
$response = json_encode(array('success' => TRUE));
header("Content-Type: application/json");
print $response;
exit;
}
js
jQuery(document).ready(function() {
jQuery('#my-show-more-form').submit(function(event) {
/* Prevent submitting normally */
event.preventDefault();
var data = {
action: 'my_more_posts',
offset: 8
};
jQuery.post(MyAjax.ajaxurl, data, function(response) {
alert('Response: ' + response);
});
});
});
Anyone got any ideas of what is wrong? Think I got all code for this.
use wp_die(); instead of exit; inside PHP callback function.
So this will be
header("Content-Type: application/json");
print $response;
wp_die();