I'm trying to call a list of my Wordpress posts and save them to a Javascript array of objects (JSON, really). I want something like:
var articles = [
{
title: 'Title 1',
author: 'Author 1',
byline: 'Byline 1'
},{
title: 'Title 2',
author: 'Author 2',
byline: 'Byline 2'
}
]
I'm new to PHP so don't quite understand how looping in and out of the <?php ?> tags works, nor how variables and functions work in this sense. I'm trying the following:
<script>
var articles = [];
<?php
$args = array( 'numberposts' => -1);
$posts= get_posts( $args );
if ($posts) {
foreach ( $posts as $post ) { ?> // exit PHP
var obj = {}; // Create a JS object
obj.title = <?php the_title(); ?>; // Append the title to the object
obj.byline = <?php the_excerpt(); ?>; // Append the byline
articles.push(obj); // Push object into the array
<?php }
}
?>
</script>
Related
I'm working on a calendar for wordpress, so I have the following issue: the data i get from the query does not match the datepicker format
The parts to acquire the arrays are following
<?php
$my_array = array();
// the query
$args=array(
'post_type' => 'eventos',
'order'=>'ASC');
$posts = get_posts( $args );
if ( $posts ) {
foreach ( $posts as $post ) {
$my_array[] = array(
'Title' => $post->post_title,
'Date' => date_format(date_create('#'. strtotime(get_field('data-event'))), 'r') . "\n"
,
);
}
}
print_r($my_array);
?>
var events = [
{ Title: "Evento 1", Date: new Date("05/20/2020")},
{ Title: "Evento 2", Date: new Date("05/20/2020")},
{ Title: "Evento 3", Date: new Date("05/21/2020")},];
ConsoleLog Image
any ideas how can I make them equal?
How do i show multiple database entries in loop ? So that it looks like this:
But with multiple markers.
I'm not able to loop javascript in php to show multiple markers. Is it possible to do so?
dataProvider: {
map: "worldLow",
images: [
<?php include ('query.php');
while($row= mysql_fetch_array($fetch)){
$cty = $row['city'];
$lat = $row['lati'];
$lon = $row['longi'];
}?>
{
zoomLevel: 5,
scale: 0.5,
title: "<?php echo $cty;?>",
latitude: <?php echo $lon;?>,
longitude: <?php echo $lat;?>
}]
}
I advise you to use json_encode function so as to avoid problems with extra quotes and other symbols:
dataProvider: {
map: "worldLow",
<?php include ('query.php');
// store all markers here
$markers = array();
while ($row= mysql_fetch_array($fetch)) {
// add new marker data
$markers[] = array(
'zoomLevel' => 5,
'scale' => 0.5,
'title' => $row['city'],
'latitude' => $row['lati'],
'longitude' => $row['longi'],
);
}?>
images: <?=json_encode($markers)?>
}
For further debugging - use developers console and/or see rendered javascript.
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();
I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);
I have just discovered this awesome wordpress function
<?php echo 'Number of posts published by user: ' . count_user_posts( ); ?>
Im busy making a graph which displays on a pie chart how many posts the user has done per category. (chars.js)
Is there any way to make a loop almost where i could get the values for each category the user has posted in.
Id like to future proof it so if more categories are added i dont have to go and write something like this
<?php echo 'Number of posts published by user: ' . count_user_posts( 5 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 7 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 8 ); ?>
Is there a way where i can just get a category breakdown of how many posts a user has posted in all categories
Thanks for any help
Try this code:
Just set which type of user's do you want at array:
<?php $args = array(
'blog_id' => $GLOBALS['blog_id'],
'role' => 'subscriber',//"Super Admin" or "Administrator" or "Editor" or "Author" or "Contributor"
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'meta_query' => array(),
'include' => array(),
'exclude' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'search' => '',
'number' => '',
'count_total' => false,
'fields' => 'all',
'who' => ''
);
php get_users( $args );
foreach ($blogusers as $user) { ?>
<li>
<?php $user_id = $user->ID ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( $user_id ); ?>
</li>
<?php } ?>
Thanks.
I think you are misunderstanding the count_user_posts function. It's argument is for user id and not for category id.
Anyways, once you have the desired user id (if i understood well, you want to display the post count for every category where the user was the post author) you can do something like this:
$user_id = 124;
/* Get all categories */
$categories = get_terms("category");
/* Loop for each category to count the posts of the user */
foreach($categories as $category)
{
$cat_name = $category->name;
$cat_id = $category->term_id;
$post_count = count(get_posts("cat=$cat_id&post_author=$user_id"));
echo "The user $user_id has $post_count posts in the $cat_name category";
}
Here is the completed code, thanks for the help everyone
<script type="text/javascript">
var pieData = [
<?php
$user_id = get_query_var('author');
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
//get all posts from author
$args = array(
'post_type' => 'post',
'author'=> $queried_object->ID
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//put categories in array
$cat = get_the_category( get_the_ID() );
$terms[] = $cat[0]->term_id;
endwhile;
wp_reset_query();
endif;
//count matching categories (array vals)
$countVal = array_count_values($terms);
foreach($countVal as $count){
$color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
echo " {
value: ".$count.",
color:'".$color."'
},";
}
?>
]
var myPie = new Chart(document.getElementById("piec").getContext("2d")).Pie(pieData);
</script>