Add File Attachment Name and URL into Javascript - javascript

I'm working on incorporating the jPlayer into our WordPress site. I don't particularly care for the two plugins that are available as our client is a bit on the technically deficient side. What we are looking to accomplish is have the Title and Mp3 load into the JavaScript for the jPlayer playlist. Currently everything is loading just fine and returning the appropriate texts, however I'm unable to get the File Name and the Attachment URL to load appropriately. I'm fairly new to java and wordpress for that matter. If you would like to see a live site example, please visit http://www.ourgoodfight.com/?p=6054
<!--Begin Jplayer Playlist -->
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
}, [
<?php
global $post;
$jukebox_args = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_mime_type' => 'audio/mpeg',
'orderby' => 'menu_order',
'order' => 'ASC',
'post_parent' => $post->ID
));
$the_jukebox_query = new WP_Query( $jukebox_args );
?>
<!--This is what needs to loop -->
<?php
$loop = new WP_Query( $jukebox_args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
{
title:<?php echo apply_filters( 'the_title', $attachment->post_title ); ?>,
mp3:<?php echo wp_get_attachment_url( $attachment->ID, false ); ?>,
},
<?php endwhile;?>
<!--This would be the end of the loop -->
], {
swfPath: "<?php echo get_template_directory_uri(); ?>/js",
supplied: "mp3",
wmode: "window"
});
});
//]]>
</script>

You are attempting to use the var $attachment to access your attachments data. But you don't ever set your $attachment var to actually contain any data, so its currently empty. As you have set up your post data within your loop using $loop->the_post(); you should be able to;
title:<?php echo apply_filters( 'the_title', get_the_title() ); ?>,
mp3:<?php echo wp_get_attachment_url( get_the_ID(), false ); ?>,
http://codex.wordpress.org/Class_Reference/WP_Query
Take note of the point about re setting your post data using wp_reset_postdata().

Related

AJAX pagination not loading in new posts (admin-ajax not found)

I have a custom post type built in WordPress named Knowledge.
Knowledge currently only has 4 posts in total. By default, 3 posts are shown, then on load more click, I want the last, 4th blog card to show.
However, currently, my AJAX request isn't succeeding, it gives me the /wp-admin/admin-ajax.php 403 (Forbidden) error. Similar questions stated that it might be related to security plugins. However, I have disabled any security related plugins (Jetpack) and the error still exists.
Here is my approach so far:
knowledge-listing.php
<?php
global $post;
$args = array(
'post_type' => 'knowledge',
'posts_per_page' => 3,
'post_status' => 'publish',
'orderby' => 'publish_date',
'order' => 'DESC'
);
$query = new WP_Query($args);
if ($query->have_posts()):
while ($query->have_posts()):
$query->the_post();
get_part('templates/snippets/knowledge-card', array(
'heading' => get_the_title() ,
'subheading' => get_the_excerpt() ,
'background' => wp_get_attachment_url(get_post_thumbnail_id($post->ID)) ,
));
endwhile;
wp_reset_postdata(); ?>
<div class="knowledgeListing__loadmore">
<a href="#" id="loadmore" class="button--loadmore" data-type="knowledge" data-max-num-pages="<?php echo $query->max_num_pages; ?>">
<?php echo _e('Load More', 'theme'); ?>
</a>
</div>
<?php
endif; ?>
loadmore.js
jQuery(function($){
$(document).ready(function(){
$("#loadmore").on('click', function (e) {
e.preventDefault();
var btn = $(this);
showNextItems(btn);
});
function showNextItems(btn) {
var max_num_pages = btn.data('max-num-pages');
var post_type = btn.data('type');
var button = btn,
data = {
'action':'loadmore',
'query': loadmore_params.posts,
'page' : loadmore_params.current_page,
// 'security' : loadmore_params.security,
// 'max_num_pages' : max_num_pages,
// 'post_type' : post_type
};
$.ajax({
url : loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success : function( data ){
if( data ) {
button.text( 'Load More' ).prev().before(data);
loadmore_params.current_page++;
$('.knowledgeListing__wrapper').find('.knowledgeCard').last().after( data );
if ( loadmore_params.current_page == max_num_pages ){
button.remove();
}
console.log("success");
} else {
button.remove();
}
},
error : function(error){
button.text( 'Load More' );
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
// console.log(error);
}
});
}
});
});
The following two console.log's spit out [object Object]
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
Unsure where things are going wrong?
Edit:
console.log("Data:", data) and console.log("loadmore_params:", loadmore_params); results below:
On further inspection, when trying to access the /wp-admin/admin-ajax.php url, I see a 0. When searching for this online, it has been suggested to use die(). However, when I've added die() to the end of knowledge-listing.php, it still shows me a 0.
Here is my localized script for reference:
global $wp_query;
wp_localize_script( 'theme', 'loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'security' => wp_create_nonce("load_more")
) );
And actions:
add_action('wp_ajax_loadmore', 'pagination_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'pagination_ajax_handler'); // wp_ajax_nopriv_{action}
Just my 2 cents but "loadmore" as an action name is quite common and may be used by some other plugins/theme function. You should really consider switching to something namespaced like wp_ajax_mypluginname_loadmore.
That said, another common issue is that you perform the add_actions too late or maybe they never get hit by code before wp-admin-ajax does his thing.
Please be 100% you hit the add_actions BEFORE the code enter wp-admin-ajax.
To make a quick test you could move those line (included the function) in your child-theme functions.php file

List all posts in custom post type by taxonomy not working

I am trying to get a list of all the posts in custom post type by taxonomy, I am stuck 3 days at this code, now i study with my father and he gave me a hint why my code is'nt working he a said i have too many args i will show you the code i hope anyone can help me understand why its not working and maybe if you really kind a explanation of the code in english
print_r(Array(
"1"=>"first",
"2"=>"second"
));
// just try to remove args that you don't need
//actually you need only one
$args = array(
'tax_query' => array(
'taxonomy' => 'your-custom-taxonomy',
'field' => 'slug',
'terms' => array( 'your-term' )
),
'post_type' => 'your-post-type'
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li>'.get_the_title().'</li>';
endwhile;
}
So you have a custom post type called your-post-type
and you have a custom taxonomy called your-custom-taxonomy and you
want to get all the posts with a taxonomy term set called your-term.
You are doing it the right way with setting your arguments.
Notice: If you want to get all the posts of a custom post type, you do not need the whole 'tax_query' part of code.
I added some comments to describe what the code is doing:
$args = array( // define your arguments for query
'post_type' => 'your-post-type', // standard post type is 'post', you use a custom one
'tax_query' => array( // you check for taxonomy field values
array(
'taxonomy' => 'your-custom-taxonomy', // standard is 'category' you use a custom one
'field' => 'slug', // you want to get the terms by its slug (could also use id)
'terms' => 'your-term', // this is the taxonomy term slug the post has set
),
),
);
$loop = new WP_Query( $args ); // get post objects
// The Loop
if ( $loop ->have_posts() ) { // check if you received post objects
echo "<ul>"; // open unordered list
while ( $loop ->have_posts() ) { // loop through post objects
$loop ->the_post();
echo '<li>'.get_the_title().'</li>'; // list items
}
echo "</ul>"; // close unordered list
/* Restore original Post Data */
wp_reset_postdata(); // reset to avoid conflicts
} else {
// no posts found
}
Hope this helps!
EDIT: If you do not know how to use WP_Query
This code will get your wordpress posts ordered by their titles and output title and content. Put this inside a template file of your theme (learn something about template files: https://developer.wordpress.org/themes/basics/template-hierarchy/).
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1, // limit the number of posts if you like to
'orderby' => 'title',
'order' => 'ASC'
);
$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) : while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content();?>
<?php endwhile; else : ?>
<p>No posts</p>
<?php endif; wp_reset_postdata(); ?>
You said you want to use a custom post type and do a taxonomy query. So you can adjust this with changing the arguments in $args.

Executing nested <script> tags in PHP

I am working on a side project for my website to make the footer more easily editable in the Wordpress theme customizer, and use a dynamic copyright date, something I had in my previous version, but I wanted the values to be more easily editable.
I have created all of this and it works fine, but when I try to add in the dynamic date, it falls over as when I do this, I am trying to have a within a .
I have looked around quite a bit for an answer to this, but not knowing what to call it doesn't help.
I decided asking my question directly is probably the best thing to do.
So, inside a php script, I have all the values I need which work fine, and a at the bottom which uses jQuery to append HTML code to a certain area (after the #footer-info area).
I need to be able to use the small amount of code posted below in the area indicated, but have no idea how to do this as it is technically inside a jQuery string.
This is the main area which I need:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#footer-info").text(' ');
jQuery('<p id="footer-info"><?php if( !empty($footer_one)) : ?><?php echo $footer_one; ?><?php endif; ?> <?php if( !empty($footer_two)) : ?><?php echo $footer_two; ?><?php endif; ?> | © Copyright <?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>**DYNAMIC DATE** <?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>. All Rights Reserved.</p>').insertAfter("#footer-info");
});
</script>
The dynamic date code:
<script>new Date().getFullYear()><?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>&&document.write(" - "+new Date().getFullYear());</script>
I need a way to put the code above inside the area marked DYNAMIC DATE in the first code segment (just past half-way through scrolling).
Is this possible, or am I doing this all wrong?
Here is the whole php file if you need it:
<?php
// ====================== Footer Editor ======================
function ds_footer_links_editor($wp_customize) {
$wp_customize->add_panel( 'footer_links_option', array(
'priority' => 30,
'capability' => 'edit_theme_options',
'title' => __('Edit Footer Links', footer_links_title),
'description' => __('Customize the login of your website.', footer_links_title),
));
$wp_customize->add_section('ds_footer_links_section', array(
'priority' => 5,
'title' => __('Footer Links Editor', footer_links_title),
'panel' => 'footer_links_option',
));
// Before Link One
$wp_customize->add_setting('ds_footer_links_before_link_one', array(
'default' => 'Designed By',
'type' => 'option',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control('ds_footer_links_before_link_one', array(
'label' => __('Text Before First Link', footer_links_title),
'section' => 'ds_footer_links_section',
'type' => 'option',
'priority' => 5,
'settings' => 'ds_footer_links_before_link_one'
));
// Link One
$wp_customize->add_setting('ds_footer_links_link_one', array(
'default' => 'Kyle Briggs',
'type' => 'option',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control('ds_footer_links_link_one', array(
'label' => __('First Link Text', footer_links_title),
'section' => 'ds_footer_links_section',
'type' => 'option',
'priority' => 10,
'settings' => 'ds_footer_links_link_one'
));
// Link One URL
$wp_customize->add_setting('ds_footer_link_one_url', array(
'default' => 'http://kylebriggs.co.uk/',
'type' => 'option',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control('ds_footer_link_one_url', array(
'label' => __('First Link URL', footer_links_title),
'section' => 'ds_footer_links_section',
'type' => 'option',
'priority' => 15,
'settings' => 'ds_footer_link_one_url'
));
// Company Name
$wp_customize->add_setting('ds_footer_links_company_name', array(
'default' => 'Kyle Briggs',
'type' => 'option',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control('ds_footer_links_company_name', array(
'label' => __('Text Before First Link', footer_links_title),
'section' => 'ds_footer_links_section',
'type' => 'option',
'priority' => 5,
'settings' => 'ds_footer_links_company_name'
));
//Company URL
$wp_customize->add_setting('ds_footer_link_company_url', array(
'default' => 'http://kylebriggs.co.uk/',
'type' => 'option',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control('ds_footer_link_company_url', array(
'label' => __('First Link URL', footer_links_title),
'section' => 'ds_footer_links_section',
'type' => 'option',
'priority' => 15,
'settings' => 'ds_footer_link_company_url'
));
//Start copyright year
$wp_customize->add_setting('ds_footer_link_start_year', array(
'default' => '2015',
'type' => 'option',
'capability' => 'edit_theme_options',
));
$wp_customize->add_control('ds_footer_link_start_year', array(
'label' => __('First Link URL', footer_links_title),
'section' => 'ds_footer_links_section',
'type' => 'option',
'priority' => 15,
'settings' => 'ds_footer_link_start_year'
));
}
add_action('customize_register', 'ds_footer_links_editor');
function ds_new_bottom_footer() {
$footer_one = get_option('ds_footer_links_before_link_one','Designed By');
$footer_two = get_option('ds_footer_links_link_one','Kyle Briggs');
$footer_link_one = get_option('ds_footer_link_one_url','http://kylebriggs.co.uk/');
$footer_three = get_option('ds_footer_links_company_name','Kyle Briggs');
$footer_link_two = get_option('ds_footer_link_company_url','http://kylebriggs.co.uk/');
$footer_four = get_option('ds_footer_link_start_year','2015');
?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#footer-info").text(' ');
jQuery('<p id="footer-info"><?php if( !empty($footer_one)) : ?><?php echo $footer_one; ?><?php endif; ?> <?php if( !empty($footer_two)) : ?><?php echo $footer_two; ?><?php endif; ?> | © Copyright <?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?><script>new Date().getFullYear()><?php if( !empty($footer_four)) : ?><?php echo $footer_four; ?><?php endif; ?>&&document.write(" - "+new Date().getFullYear());</script> <?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>. All Rights Reserved.</p>').insertAfter("#footer-info");
});
</script>
<?php
}
add_action( 'wp_head', 'ds_new_bottom_footer' );
?>
You have to use eval() to execute any script code that you've inserted as DOM text.
MooTools will do this for you automatically, and I'm sure jQuery would as well (depending on the version. jQuery version 1.6+ uses eval). This saves a lot of hassle of parsing out tags and escaping your content, as well as a bunch of other "gotchas".
Generally if you're going to eval() it yourself, you want to create/send the script code without any HTML markup such as , as these will not eval() properly.
Let we assume, we have following values for those variables.
<?php
$footer_one= "Footer one";
$footer_link_one= "#";
$footer_two = " link";
$footer_three = "Footer three";
?>
<script type="text/javascript">
$(document).ready(function(){
$("#footer-info").html('<?php if( !empty($footer_one)) : ?><?php echo $footer_one; ?><?php endif; ?>'+'<?php if( !empty($footer_two)) : ?><?php echo $footer_two; ?><?php endif; ?> | © Copyright <?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>**DYNAMIC DATE** <?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>. All Rights Reserved. ');
});
</script>
I don't know what below part is doing. Can you explain.
<script>new Date().getFullYear()><?php if( !empty($footer_three)) : ?><?php echo $footer_three; ?><?php endif; ?>&&document.write(" - "+new Date().getFullYear());</script>

Jquery and PHP , autocomplete

So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();

Query custom post type with jQuery.load()

Im working on a site see here and I created a custom post type named "projects".
When the page initially loads, Everything works fine, all the post data is loaded. But when I use $.load() to load the same code from an external file nothing gets displayed. It only appears to be a problem with custom post types, if I subsitute "projects" with "post" (the default type) the "Hello World" post will be re-queried,but not the "projects".
How can I query a custom post type twice? Here's my code:
<?php
$args = array(
'post_type' => 'projects',
'tax_query' => array(
'taxonomy' => 'nonfiction'
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ):
while ( $query->have_posts() ):
$query->the_post();
$meta_data = array(
'author' => get_post_meta($post->ID, 'Author', true),
'publisher' => get_post_meta($post->ID, 'Publisher', true),
'year' => get_post_meta($post->ID, 'Year', true),
'role' => get_post_meta($post->ID, 'Role', true),
'location' => get_post_meta($post->ID, 'Location', true)
);
?>
<li>
<?php
echo $meta_data['author'];
echo ". ";
the_title();
echo " (" . $meta_data['location'] . ": " . $meta_data['publisher'] . ", " . $meta_data['year'] . "). " . $meta_data['role'];
?>
</li>
<?php
endwhile;
endif;
?>
$(document).ready(function(){
$('.tab').click(function(){
$('.publications').load('http://greyediting201.staging.wpengine.com/wp-content/themes/pp_boot/_nonfiction.php', null, console.log('finished'));
});
});
Yes in .load() function do not use server url but relative path such as ./path of js folder/js file.js. hope it will work for you
Just check the link here for jquery docs
i think .load work in relative urls only otherwise any cross-domain issuses

Categories

Resources