Using wordpress I am grabbing the first image attachment from the posts. This works fine:
<?php
global $post;
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 2 );
$images = get_posts($args);
if ( $images ) {
$i = 0;
while($i <= 1){
$image = wp_get_attachment_url( $images[$i]->ID );
echo "<img src='$image' />";
$i++;
}
}
?>
I am also trying to process these images which in conjunction with timthumb resizes the images depending on browser size. I can only get this to work on one of the two images. I would expect it to log and resize twice but the script is not running in the loop. Can someone please help ? This is what the full snip I am working with looks like :
<?php
global $post;
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 2 );
$images = get_posts($args);
if ( $images ) {
$i = 0;
$z = 1;
while($i <= 1){
$image = wp_get_attachment_url( $images[$i]->ID );
echo "<img src='$image' class='image_$z' />";
?>
<script type="text/javascript">
var image = "<?php echo $image ; ?>";
var under700_<? echo $z ?> = "/wp-content/themes/Loupe/scripts/timthumb.php?src=<? echo $image ?>&w=340";
var under900_<? echo $z ?> = "/wp-content/themes/Loupe/scripts/timthumb.php?src=<? echo $image ?>&w=440";
function imageresize() {
var contentwidth = $('#two_up').width();
if ((contentwidth) < '700'){
console.log('under 700_<? echo $z ?>' + under700_<? echo $z ?>);
$('img .image_<? echo $z ?>').attr('src', under700_<? echo $z ?>);
} else if ((contentwidth) < '900') {
// console.log('under 900');
$('img .image_<? echo $z ?>').attr('src', under900_<? echo $z ?>);
}
else {
image;
}
}
</script>
<?php
$i++;
$z++;
}
}
?>
Use json_encode() it makes a JavaScript object (or array or combined) of a PHP variable and makes it
I'm assuming $images is an array; if not, tweak this solution to fit.
Javascript:
var images = <? echo json_encode($images); ?>;
for( x=0; x<images.length-1; x++)
{
someFunction(images[x]);
}
I would recommend setting specific height/width in your css and then using jquery to replace the images as the page loads.
As an alternative, try doing the entire processing in php. You'll save your users loading time, and imho, it's much easier.
http://www.imagemagick.org/script/index.php
What I guess you are trying to do is something like this:
<?php
global $post;
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 2
);
$images = get_posts($args);
if ( $images ) {
$i = 0;
?>
<script type="text/javascript">
function imageresize(imgElement, srcString) {
var under700 = "/wp-content/themes/Loupe/scripts/timthumb.php?src=" + srcString + "&w=340";
var under900 = "/wp-content/themes/Loupe/scripts/timthumb.php?src=" + srcString + "&w=440";
var contentwidth = $('#two_up').width();
if ((contentwidth) < '700'){
console.log('under 700' + under700);
$(imgElement).attr('src', under700);
imgElement.onload = ''; //stop the onload event from happening again
} else if ((contentwidth) < '900') {
// console.log('under 900');
$(imgElement).attr('src', under900);
imgElement.onload = ''; //stop the onload event from happening again
}
else {
image; //don't know what to make of this (maybe you do)
}
}
</script>
<?php
while($i < count($images)){
$image = wp_get_attachment_url( $images[$i]->ID );
echo "<img src='$image' class='image' onload='imageresize(this, \"$image\")' />";
$i++;
}
}
?>
But, as suggested before by #Toast: I'd do this in PHP and prevent the user from reloading all the images on the page. Because that is effectively done by the above code.
If you have the path of the source image files that you are trying to resize, then you could use getimagesize to get the image size, and adjust the src uri off the images accordingly.
The only guess I have, at you using javascript to do this, is that you are using the DHTML/CSS box model to help you calculate the width of the container (#two_up) for the images. This I would strongly discourage, but still the above code should work! ;)
Related
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.
This is puzzling me for the past hours already. Hopefully anybody has the clearing answer and in any case, thank for any support. In need to filter between three values in a data-attribute, which are set in jQuery. These values are changed and put in the attribute, depending on screenwidth. The jQuery part works fine. Now the tricky part is that in the PHP file the right value of the data-width attribute should be used and put as a value for a custom field. This value triggers the right images in a backgroundslider.
I tried the if/else statement in which the attribute value had a variable, which could give the right value for the custumfield, when its value would be equal as the one mad in jQuery. This failed. My knowledge is limited and therefore my files looked like this.
jQuery:
function schermFilter() {
var scherm = $(window).width();
if (scherm >= 320 && scherm <= 480) {
$('#homeslider-wrapper').attr('data-width','slides_mobiel')
console.log(scherm + ": mobiel");
} else if (scherm >= 768 && scherm <= 992) {
$('#homeslider-wrapper').attr('data-width','slides_tablet')
console.log(scherm + ": tablet");
} else {
$('#homeslider-wrapper').attr('data-width','slides_groot')
console.log(scherm + ": groot");
}
};
schermFilter();
$(document).ready(function() {
schermFilter();
});
PHP:
<?php $screenwidth =""; ?>
<?php $args = array(
'post_type' => 'homeslides',
'order' => 'date'
);
$slider = new WP_QUERY($args);
if($slider->have_posts()) : ?>
<div id="homeslider-wrapper" class="slides" data-width="$screenwidth">
<?php while ($slider->have_posts()) : $slider->the_post(); ?>
<?php if ($screenwidth === "slides_mobiel") {
$image = get_field('slides_mobiel');
echo $screenwidth;
} elseif ($screenwidth === "slides_tablet") {
$image = get_field('slides_tablet');
echo $screenwidth;
} else if ($screenwidth === "") {
$image = get_field('slides_groot');
echo $screenwidth;
} else {
$image = get_field('slides_groot');
echo "groot - else";
}
?>
<?php $imageList .= '"'. $image['url'] . '",'; ?>
<?php endwhile; ?>
</div>
<?php endif;wp_reset_postdata(); ?>
<?php $imageList = rtrim($imageList, ','); ?>
I tried isset and property-exists, but without success. Thanks!
I'm using the prettyPhoto API to open the the lightbox manually with the following code:
api_images ['images/fullscreen/image1.jpg','images/fullscreen/image2.jpg','images/fullscreen/image3.jpg'];
api_titles = ['Title 1','Title 2','Title 3'];
api_descriptions = ['Description 1','Description 2','Description 3']
$.prettyPhoto.open(api_images,api_titles,api_descriptions);
The problem i'm facing is that the description values are pulling from Wordpress's WYSIWYG and the code is easily broken with random html tags, punctuation etc
<script type="text/javascript">
$(document).ready(function() {
$('#menu-item-1006').on('click', function(e) {
e.preventDefault();
var images = new Array();
var descriptions = new Array();
var titles = new Array();
<?php
$i = 0;
$images = new WP_Query(array('post_type' => 'clearance', 'showposts' => -1, 'order' => 'menu_order', 'orderby' => 'ASC'));
if ($images->have_posts()) : while ($images->have_posts()) : $images->the_post();
$featured = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
?>
images[<?php echo $i; ?>] = '<?php echo $featured[0]; ?>';
titles[<?php echo $i; ?>] = '<?php the_title(); ?>'
descriptions[<?php echo $i; ?>] = '<?php echo get_the_content(); ?>';
<?php
$i++;
endwhile;
else:
?>
<?php endif; ?>
$.prettyPhoto.open(images, titles, descriptions);
})
});
</script>
How can i filter the get_the_content() function so it will output w/o errors? Thanks!
a simple solution could be:
replace
<?php echo get_the_content(); ?>
with
<?php echo preg_replace('/\<[^\>]+\>/s', '', get_the_content()); ?>
json_encode(get_the_content()) works!
$content = get_the_content();
echo strip_tags($content, '<a><img>');
will leave only a and img tags. I think it's all what you need for gallery
I have a 25 advertiserids from CJ and now I want to create 2 post in different category of wordpress from each advertiserid given. So I have created following script but it is not pausing for user input, so how can I do that ?
If its not possible with while then is there any other method to do this ? in script $ad is array with advertiser's id value and $adcat is also a array with advertiser's catagory
function cjlinks($n)
{
global $ad, $adcat;
$URI = 'https://product-search.api.cj.com/v2/product-search?website-id=12345678'.
'&advertiser-ids='.$ad[$n].
'&records-per-page=2';
$context = stream_context_create(
array(
'http' => array(
'method' => 'GET',
'header' => 'Authorization: ' .
'my api id'
)
));
$res = new SimpleXMLElement(file_get_contents($URI, false, $context));
return $res;
}
$a = 0;
while ($a < 25)
{
echo 'advertiser id is: '.$ad[$a].'<br/>advertiser - catagory is: '.$adcat[$a]->child.
'<br/>';
if (isset($_SESSION['sumit'])){
$data = cjlinks($a);
$attributes = $data->products->attributes();
if ($attributes->{'total-matched'} == 0){
echo 'No products found ...try again with new keyword.';
}else{
foreach ($data->products[0] as $product)
{
// Sanitize data.
$price = number_format((float)$product->price, 2, '.', ' ');
$image = '<img src="'.$product->{'image-url'} .'" style="float: right"/>';
$pd = $image.$product->description .'<a href="'.$product->{'buy-url'}.
'">...For more details and to buy it click here</a>';
$p = array('post_title' => $product->name,
'post_content' => $pd,
'post_status' => 'publish',
'post_author' => 1,
'post_category' =>array($_GET['cat']));
$pr = wp_insert_post( $p, $wp_error );
echo '<br/>posted...post ID is:'.$pr;
wp_reset_query(); // Restore global post data stomped by the_post().
}
}
}else{
echo 'please complete form';
$a = $a+1;
}
}
?>
<html>
<body>
<form action="catag.php" method="get">
<table>
<tr>
<td><label> Select a catagory from list:</label></td></tr>
<tr>
<?php
foreach($cat as $key=>$val){
echo '<tr><td><input type="radio" value="'.$val->cat_ID.'" name="cat" id="'.$val->cat_ID.'">'.$val->cat_name.'</td></tr>';
}
?>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form><br>
</body>
</html>
You can not literally "pause" a php script, as php is executed on the server before the page even loads.
To execute any kind of a "pause" you would need to write your function in Javascript or other Client Side (Browser Executed) code, or send something like an Ajax request to a php page that would then update the current page on response.
I am having issue with a wordpress Tag CLoud Plugin.
I want to show random tags but i am confused how to do this.
the codes are given below.
I want to show random tags. like if i select to show just 5 tags and when each time i refrest the screen the tags should appear randomly.
function widget_tagcloud($args){
$option_value = retrieve_options($opt_val);
extract($args);
echo $before_widget;
echo $before_title;
echo $option_value['title'];
echo $after_title;
global $wpdb;
$tags_list = get_terms('post_tag', array(
'orderby' => 'count',
'hide_empty' => 0
));
if(sizeof($tags_list)!=0){
$max_count = 0;
if(!empty($option_value['height'])) $canvas_height = $option_value['height'];
else $canvas_height = "250";
if(!empty($option_value['width'])) $canvas_width = $option_value['width'];
else $canvas_width = "250";
foreach($tags_list as $tag) if($tag->count > $max_count) $max_count = $tag->count;?>
<div id="myCanvasContainer">
<canvas width="<?php echo $canvas_width;?>" height="<?php echo $canvas_height;?>" id="myCanvas">
<p>Tags</p>
</canvas>
</div>
<div id="tags">
<ul style="
font-family: <?php if(!empty($option_value['font_name'])) echo $option_value['font_name'];
else echo "Calibri";?>;
height:
<?php
if(!empty($option_value['height'])) echo $option_value['height'];
else echo "250";
?>px;
width:
<?php
if(!empty($option_value['width'])) echo $option_value['width'];
else echo "250";
?>px;
background-color: #<?php if(!empty($option_value['bg_color'])) echo $option_value['bg_color'];
else echo "FFF";?>;
">
<?php
if(empty($option_value['no_of_tags'])) $option_value['no_of_tags'] = 15;
if(empty($option_value['txt_color'])) $option_value['txt_color'] = "000";
if(empty($option_value['max_font_size'])) $option_value['max_font_size'] = 40;
if(empty($option_value['min_font_size'])) $option_value['max_font_size'] = 3;
$i=1;
foreach($tags_list as $tag){
if($i <= $option_value['no_of_tags']){
$font_size = $option_value['max_font_size'] - (($max_count - $tag->count)*2);
if($font_size < $option_value['min_font_size']) $font_size = $option_value['min_font_size'];
echo '<li><a href="'.$_SERVER['PHP_SELF'].'?tag='.$tag->slug.'"
style="font-size:'.$font_size.'px;color: #'.$option_value['txt_color'].';">'
.$tag->name.'</a></li>';
$i++;
}
}
echo '</ul></div>';
}
else echo "No tags found";
echo $after_widget;
}
Accordind to your code: (this part especially)
$tags_list = get_terms('post_tag', array(
'orderby' => 'count',
'hide_empty' => 0
));
The tags which you get are ordered by count , therefore - they are not randomly picked.
You can try and use the next code:
$tags_list = get_terms('post_tag', array(
'number' => 5,
'orderby' => 'none',
'hide_empty' => 0
));
And if that doesn't work , build a customized query using the RAND function of mysql.
EDIT: based on your code , you can do is even easier by using the shuffle() php function.
Just replace:
$max_count = 0;
With:
$max_count = 5;
shuffle($tags_list);