• Resolved accountnotinuse

    (@lionsdendesigns)


    Hello!

    Need help with my code. I have several PDFs and PPTs all named by their date in the filename. YYYY-M-D.pdf with no leading zeros. I would like today’s date of M-D to match the filename’s M-D and use substr() to remove the first five characters of the filename to check for the match. Then it needs to list only those that match the today’s date and provide a link that opens in a new window. Each link is separated by a space and showing the full filename without the extension, using glob() to find a match if necessary.

    <?php
    date_default_timezone_set('America/New_York');
    $todayNoYear = date('n-j'); // Month - Day
    $args = array( 'post_mime_type' => 'application/pdf', 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => null );
    $attachments = get_posts( $args );
    $attachmentTitle = apply_filters( 'the_title' , $attachment->post_title );
    $titleNoYear = substr($attachmentTitle, 5);
    if ($attachments) {
    	if ($todayNoYear == $titleNoYear) {
    		echo 'PDF for Today: ';
    
    		foreach ( $attachments as $attachment ) {
    			$attlink = the_attachment_link($attachment->ID, false);
    			echo $attlink.'&nbsp;';
    		}
    	} else {echo 'none';}
    }	 
    
    ?>
Viewing 11 replies - 1 through 11 (of 11 total)
  • Moderator bcworkz

    (@bcworkz)

    You seem to have the right idea about matching up date strings, if it’s not working right, try checking the date variable values with print_r(). It should be apparent what’s wrong and how to alter your script to get them to match up.

    The real problem right now is you are not getting a title at all because your program flow is mixed up. I’ve rearranged your script into logical order, but haven’t checked for other errors. It’s a start anyway.

    //lines above here OK?
    $attachments = get_posts( $args );
    if ($attachments) {
    	foreach ( $attachments as $attachment ) {
    		$attachmentTitle = apply_filters( 'the_title' , $attachment->post_title );
    		$titleNoYear = substr($attachmentTitle, 5);
    		if ($todayNoYear == $titleNoYear) {
    			echo 'PDF for Today: ';
    				$attlink = the_attachment_link($attachment->ID, false);
    				echo $attlink.'&nbsp;';
    		} else {echo 'none';}
    	}
    }
    Thread Starter accountnotinuse

    (@lionsdendesigns)

    @bcworkz

    Thank you so much!

    That print_r() helped set my bearings. Of course, had to look it up to find how to use it. ^__^
    Helpful link: http://php.about.com/od/phpfunctions/g/print_r_php.htm

    Here’s my final code that I put in the header:

    <?php
    date_default_timezone_set('America/New_York');
    $todayNoYear = date('n-j'); // Month - Day
    $args = array( 'post_mime_type' => 'application/pdf', 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => null );
    $attachments = get_posts( $args );
    if ($attachments) {
    	foreach ( $attachments as $attachment ) {
    		$attachmentTitle = apply_filters( 'the_title' , $attachment->post_title );
    		$titleNoYear = substr($attachmentTitle, 5); //filename naming convention is YYYY-M-D.pdf or .ppt or .pptx with no leading zeros  so this 2013-8-8.pdf instead of this 2013-08-08.pdf, this 5 takes off the YYYY-
    		if ($todayNoYear == $titleNoYear) {
    			echo 'PDF for Today: ';
    				$attlink = the_attachment_link($attachment->ID, true);
    				echo $attlink;
    
    		}
    	}
    }
    ?>

    Now, I need to figure out how to get three specified post_mime_type : pdf, ppt, pptx


    Keywords to help me search for this again:
    unattached media library attachments today current date if today then show filename

    Thread Starter accountnotinuse

    (@lionsdendesigns)

    I want to make this code available in case someone else is trying to figure this out. I started half of it and a friend, Matt, helped me with the GLOB part. GLOB allows you to search for filenames matching specific criteria. Help here for GLOB: http://php.net/manual/en/function.glob.php This link for matching specific patterns is helpful too: http://cowburn.info/2010/04/30/glob-patterns/

    This does the same as above but it looks for a specific url, I suggest using bloginfo(wpurl) so you get both http/https and other custom permalinks correct. The only reason I’m not using it is that, on the home page it works fine but on the other WordPress pages it picks up the current page slug and puts that in the link and I don’t know how to fix that.

    If someone can show the fixed code below before this topic is marked as resolved, I’d be most appreciative towards them.

    <?php
    					// This script only checks for the existence of a file(s) (multiple extensions) by current EST date, written by Daniel Brinneman July 24, 2013, with big helps from friend, Matt, to create the GLOB code to look for multiple files
    					date_default_timezone_set('America/New_York');
    					$todayNoYear = date('n-j'); // Month - Day
    					$filePath = wp_upload_dir(); //This always give the absolute link to the uploads folder, a needed / is added in the path below to make it work. If not this then each page would pull the page slug into the link or double the link path if put in manually.
    
    					// Get each PDF with today's date, optionally with a hyphen and more characters
    					// after it before the extension.
    					$todaysPdfs = array();
    					foreach(glob($filePath['path'] . '/[0-9][0-9][0-9][0-9]-'. $todayNoYear . '{.,-*.}{pdf,ppt,pptx}', GLOB_BRACE) as $file)
    					{
    					    // If the file is readable...
    					    if(is_readable($file))
    					    {
    					        // Add it to our list.
    					        array_push($todaysPdfs, $file);
    					    }
    					}
    
    					// If there are NOT any...
    					if (count($todaysPdfs) < 1)
    					{
    					    // Say so.
    					    echo '<li class="fileoftheday-heading">|&nbsp;&nbsp;File of the Day: (none)</li></ul>';
    					}
    					// Otherwise...
    					else
    					{
    					    // Show them
    					    echo '<li class="fileoftheday-heading">|&nbsp;&nbsp;File of the Day:</li>';
    					    foreach($todaysPdfs as $pdf)
    					    {
    					        $encFileName = htmlentities($pdf, ENT_QUOTES, 'UTF-8');
    					        $encFileNameSubstr = substr($encFileName, 24); //Used to be 24: 45  Change back to 24 when the site is made live and adjust the $filePath to root starting with wp-content
    					        $encFileNameBasename = pathinfo($encFileNameSubstr, PATHINFO_FILENAME); // Remove any file extension that you don't know exists
    					        //$encFileNameBasename = basename($encFileNameSubstr, ".pdf"); // Only removes extensions you know
    					        echo '<li><a href="' . $encFileName . '" target="_blank" class="fileoftheday-link">' . $encFileNameBasename . '</a></li>';
    					    }
    					    echo '</ul>';
    					}
    
    					?>
    Thread Starter accountnotinuse

    (@lionsdendesigns)

    How do I open those attachment links in a new window?

    Please do not do this unless you pre-warn visitors – in clear text – as part of the link. Spawning new windows without warning can leave some users stranded with no way back to the site.

    Thread Starter accountnotinuse

    (@lionsdendesigns)

    @esmi

    Are you talking about links in my text or links related to the attachments code?

    If the links in the text, you should be able to right-click on the link and open it in a new window or Cmd/Ctrl click on it. Is there an option to add target=”_blank” to the links in the help text?

    I’m asking for help regarding the attachments code, opening PDF files in a new window. Any help?

    Moderator bcworkz

    (@bcworkz)

    Have you experimented with some of the other path variants returned by wp_upload_dir()? It seems at least one of them would not be picking up the page slug.

    target="_blank" is the traditional way to open new windows, though it’s deprecated in XHTML. An alternative is to use javascript’s window.open, though of course it will not work if someone has disabled javascript, probably because they were tired of scripts opening new windows πŸ˜‰

    Pay heed to esmi’s warning, seriously consider letting users decide if they want a new window or not, they’ve certainly opened PDFs before and know what happens, and know how to get back to your site if need be.

    Thread Starter accountnotinuse

    (@lionsdendesigns)

    @bcworkz
    All due respect,
    When I was learning web design, I’d always read that links on your own site shouldn’t have the target=”_blank” and those navigating away should. But for files it was easiest to set them to open in a new window so that you could download them or just keep them open to read them. In this application, it’s more about reading the file because it’s a poem then closing it and still having the site in the background, eliminates all those Back button clicks.

    I’ve tried the wp_upload_dir() while I was writing that old script but it didn’t work how I wanted it to. That’s what I remember.

    @esmi
    In regard to your warning, if you had prefaced it with: In regards to your question, you should consider this… Instead of how you started it, I thought you were just moderating my post and telling me how I should be warning others of linking to help sites, so therefore I was confused by your meaning.

    To both:
    I solved my own question. I stepped away from the computer for a few hours. When I came back, I had a different search idea and found a functions.php script on the first page of results. I used Inspect Element to see if this affected featured images and it didn’t, I haven’t checked embedded images yet. For now, this works well. I do want to vary this script between having/not having the target=”_blank” inline. While not inline I would target just the class with jQuery and add the target=”_blank” attribute.

    Here’s the link to the helpful functions.php script for attachments that worked for me. http://wpsnipp.com/index.php/functions-php/add-a-custom-class-to-wp_get_attachment_link/

    function add_class_attachment_link($html){
        $postid = get_the_ID();
        $html = str_replace('<a','<a class="wpsnipp"',$html);
        return $html;
    }
    add_filter('wp_get_attachment_link','add_class_attachment_link',10,1);

    Any feedback?

    Moderator bcworkz

    (@bcworkz)

    I’m glad you found a workable solution. Filters are a great way to customize output, as long as you want the change applied to all data passing through the filter.

    As for new windows, it’s probably not worth laboring over, but I’ll throw in one more comment. It’s just my opinion, but it’s your site, you are free to do what you want. We may have learned web design in the same era, as I learned the same thing. In my case, that was some time ago. What’s considered good or bad practice changes somewhat quickly. It also varies by the target audience of your site.

    My take on the current train of thought is users are more savvy than they were several years ago. They are generally capable of managing their own windows without sites trying to second guess their desire. Still, there are circumstances where opening a new window is warranted. In such cases, it’s polite to give some warning about what will happen when one follows a particular link. A small icon after the link might be all that’s needed.

    A small icon after the link might be all that’s needed.

    Ideally, the warning should be part of the link. This is to accomodate users whose software/user agent may offer a Links List option.

    Thread Starter accountnotinuse

    (@lionsdendesigns)

    I try to think about the audience I’m designing for and also open to learning from others.

    Well, thank you for your comments and helps.

Viewing 11 replies - 1 through 11 (of 11 total)
  • The topic ‘How To: Show Attachments only for Today matched to Filename’ is closed to new replies.