qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
179,337
<p>I'm developing a plugin that adds a new tab to the media modal, and I need to know a way trigger a refresh of the attachments tab so it shows newly added attachments. This is the code I'm using:</p> <pre><code>wp.media.view.Toolbar.Custom = wp.media.view.Toolbar.extend({ initialize: function() { _.defaults( this.options, { event: 'custom_event', close: false, items: { custom_event: { text: wp.media.view.l10n.customButton, style: 'primary', priority: 80, requires: false, click: this.addAttachment } } }); wp.media.view.Toolbar.prototype.initialize.apply( this, arguments ); }, // triggered when the button is clicked addAttachment: function(){ this.controller.state().addAttachment(); this.controller.setState( 'insert' ); // I NEED TO TRIGGER A REFRESH OF THE ATTACHMENTS TAB HERE } }); </code></pre> <p>Any help would be appreciated. The media modal documentation is almost non-existant.</p> <p>Thanks</p>
[ { "answer_id": 340494, "author": "tru.d", "author_id": 167464, "author_profile": "https://wordpress.stackexchange.com/users/167464", "pm_score": 1, "selected": false, "text": "<p>Try out:</p>\n\n<pre><code>wp.media.editor.get(wpActiveEditor).views._views[\".media-frame-content\"][0].views._views[\"\"][1].collection.props.set({ignore:(+(new Date()))})\n</code></pre>\n\n<p>Seems like there must be an easier way but that works for me in the meantime!</p>\n\n<p>A more better way to do it: </p>\n\n<pre><code>wp.media.frame.content.get('gallery').collection.props.set({‌​ignore: (+ new Date())});, \n</code></pre>\n\n<p>in this case i'm refreshing the gallery tab.</p>\n\n<p>Try both of the above codes and see which one works best for you.</p>\n" }, { "answer_id": 344045, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 2, "selected": false, "text": "<p>You can checkout this link <a href=\"https://codex.wordpress.org/Javascript_Reference/wp.media\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Javascript_Reference/wp.media</a></p>\n\n<pre><code>jQuery(function($){\n\n // Set all variables to be used in scope\n var frame,\n metaBox = $('#meta-box-id.postbox'), // Your meta box id here\n addImgLink = metaBox.find('.upload-custom-img'),\n delImgLink = metaBox.find( '.delete-custom-img'),\n imgContainer = metaBox.find( '.custom-img-container'),\n imgIdInput = metaBox.find( '.custom-img-id' );\n\n // ADD IMAGE LINK\n\n\n\naddImgLink.on( 'click', function( event ){\n\n event.preventDefault();\n\n // If the media frame already exists, reopen it.\n if ( frame ) {\n frame.open();\n return;\n }\n\n // Create a new media frame\n frame = wp.media({\n title: 'Select or Upload Media Of Your Chosen Persuasion',\n button: {\n text: 'Use this media'\n },\n multiple: false // Set to true to allow multiple files to be selected\n });\n\n\n // When an image is selected in the media frame...\n frame.on( 'select', function() {\n\n // Get media attachment details from the frame state\n var attachment = frame.state().get('selection').first().toJSON();\n\n // Send the attachment URL to our custom image input field.\n imgContainer.append( '&lt;img src=\"'+attachment.url+'\" alt=\"\" style=\"max-width:100%;\"/&gt;' );\n\n // Send the attachment id to our hidden input\n imgIdInput.val( attachment.id );\n\n // Hide the add image link\n addImgLink.addClass( 'hidden' );\n\n // Unhide the remove image link\n delImgLink.removeClass( 'hidden' );\n });\n\n // Finally, open the modal on click\n frame.open();\n });\n\n\n // DELETE IMAGE LINK\n delImgLink.on( 'click', function( event ){\n\n event.preventDefault();\n\n // Clear out the preview image\n imgContainer.html( '' );\n\n // Un-hide the add image link\n addImgLink.removeClass( 'hidden' );\n\n // Hide the delete image link\n delImgLink.addClass( 'hidden' );\n\n // Delete the image id from the hidden input\n imgIdInput.val( '' );\n\n });\n\n});\n</code></pre>\n" } ]
2015/02/25
[ "https://wordpress.stackexchange.com/questions/179337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
I'm developing a plugin that adds a new tab to the media modal, and I need to know a way trigger a refresh of the attachments tab so it shows newly added attachments. This is the code I'm using: ``` wp.media.view.Toolbar.Custom = wp.media.view.Toolbar.extend({ initialize: function() { _.defaults( this.options, { event: 'custom_event', close: false, items: { custom_event: { text: wp.media.view.l10n.customButton, style: 'primary', priority: 80, requires: false, click: this.addAttachment } } }); wp.media.view.Toolbar.prototype.initialize.apply( this, arguments ); }, // triggered when the button is clicked addAttachment: function(){ this.controller.state().addAttachment(); this.controller.setState( 'insert' ); // I NEED TO TRIGGER A REFRESH OF THE ATTACHMENTS TAB HERE } }); ``` Any help would be appreciated. The media modal documentation is almost non-existant. Thanks
You can checkout this link <https://codex.wordpress.org/Javascript_Reference/wp.media> ``` jQuery(function($){ // Set all variables to be used in scope var frame, metaBox = $('#meta-box-id.postbox'), // Your meta box id here addImgLink = metaBox.find('.upload-custom-img'), delImgLink = metaBox.find( '.delete-custom-img'), imgContainer = metaBox.find( '.custom-img-container'), imgIdInput = metaBox.find( '.custom-img-id' ); // ADD IMAGE LINK addImgLink.on( 'click', function( event ){ event.preventDefault(); // If the media frame already exists, reopen it. if ( frame ) { frame.open(); return; } // Create a new media frame frame = wp.media({ title: 'Select or Upload Media Of Your Chosen Persuasion', button: { text: 'Use this media' }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected in the media frame... frame.on( 'select', function() { // Get media attachment details from the frame state var attachment = frame.state().get('selection').first().toJSON(); // Send the attachment URL to our custom image input field. imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' ); // Send the attachment id to our hidden input imgIdInput.val( attachment.id ); // Hide the add image link addImgLink.addClass( 'hidden' ); // Unhide the remove image link delImgLink.removeClass( 'hidden' ); }); // Finally, open the modal on click frame.open(); }); // DELETE IMAGE LINK delImgLink.on( 'click', function( event ){ event.preventDefault(); // Clear out the preview image imgContainer.html( '' ); // Un-hide the add image link addImgLink.removeClass( 'hidden' ); // Hide the delete image link delImgLink.addClass( 'hidden' ); // Delete the image id from the hidden input imgIdInput.val( '' ); }); }); ```
179,339
<p>So here is my code to display the post created date:</p> <pre><code> $date_create = '&lt;div class="mydate-created"&gt;'; $date_create .= get_the_date('',$product-&gt;id); $date_create .='&lt;/div&gt;'; $output .= '&lt;/div&gt;'; $output .= '&lt;div class="mydate-created"&gt;'; $output .= get_the_date('',$product-&gt;id); $output .= '&lt;/div&gt;'; </code></pre> <p>It displays the date of post created as the following "2015-02-23"</p> <p>I know there is setting in the backend to change the date displayed.</p> <p>However is there a way to display it like "1 min ago" or " 1 hour ago"?</p> <p>Thanks!</p>
[ { "answer_id": 179343, "author": "Robert hue", "author_id": 22461, "author_profile": "https://wordpress.stackexchange.com/users/22461", "pm_score": 3, "selected": true, "text": "<p>Here you go. This goes in <code>functions.php</code></p>\n\n<p>This changes the time on your website everywhere. Now you can keep using <code>&lt;?php echo get_the_date(); ?&gt;</code> in your loop or theme files.</p>\n\n<pre><code>// Relative date &amp; time\nfunction wpse_relative_date() {\n return human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago';\n}\nadd_filter( 'get_the_date', 'wpse_relative_date' ); // for posts and pages\n// add_filter( 'get_comment_date', 'wpse_relative_date' ); // for comments\n</code></pre>\n\n<p>I added a PHP comment before <code>add_filter</code> to also change comment dates too. Because I am not sure if you want that for comments too. Remove PHP comment if needed.</p>\n" }, { "answer_id": 179344, "author": "fructurj", "author_id": 67774, "author_profile": "https://wordpress.stackexchange.com/users/67774", "pm_score": 1, "selected": false, "text": "<p>You can use <code>&lt;?php human_time_diff( $from, $to ); ?&gt;</code> to return a human readable time difference.</p>\n\n<p>Take a look at the Wordpress Codex <a href=\"http://codex.wordpress.org/Function_Reference/human_time_diff\" rel=\"nofollow\">Function Reference/human time diff</a>.</p>\n" } ]
2015/02/25
[ "https://wordpress.stackexchange.com/questions/179339", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So here is my code to display the post created date: ``` $date_create = '<div class="mydate-created">'; $date_create .= get_the_date('',$product->id); $date_create .='</div>'; $output .= '</div>'; $output .= '<div class="mydate-created">'; $output .= get_the_date('',$product->id); $output .= '</div>'; ``` It displays the date of post created as the following "2015-02-23" I know there is setting in the backend to change the date displayed. However is there a way to display it like "1 min ago" or " 1 hour ago"? Thanks!
Here you go. This goes in `functions.php` This changes the time on your website everywhere. Now you can keep using `<?php echo get_the_date(); ?>` in your loop or theme files. ``` // Relative date & time function wpse_relative_date() { return human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago'; } add_filter( 'get_the_date', 'wpse_relative_date' ); // for posts and pages // add_filter( 'get_comment_date', 'wpse_relative_date' ); // for comments ``` I added a PHP comment before `add_filter` to also change comment dates too. Because I am not sure if you want that for comments too. Remove PHP comment if needed.
179,370
<p>How can I have a post (or custom post) with a definite URL:</p> <pre><code>www.test.com/category/post-name </code></pre> <p>and a child-URL referring to a specific section of that post</p> <pre><code>www.test.com/category/post-name/sub-url </code></pre> <p>without being obliged to create a specific post related to that child-URL? </p> <p>I have a post with the URL</p> <pre><code>www.test.com/category/post-name </code></pre> <p>originated by file <code>content-product.php</code> and I want to have a child-URL like</p> <pre><code>www.test.com/category/post-name/details </code></pre> <p>originated by file <code>content-product-details.php</code> that refers/recall only a section/portion of the post.</p> <p>In few words is there a way to create the structure indicated? Or do I have to manually create for each post as many sub-post as child-URL I want to have?</p>
[ { "answer_id": 179381, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>I'd say what you need to look deeper into is the <em>Rewrite API</em> and <em>Endpoints</em>, for starters see:</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/\" rel=\"nofollow noreferrer\">Make WordPress: Rewrite endpoints API</a> </li>\n<li><a href=\"http://codex.wordpress.org/Rewrite_API\" rel=\"nofollow noreferrer\">Codex: Rewrite API</a> </li>\n<li><a href=\"http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow noreferrer\">Codex: Rewrite API/add rewrite endpoint</a> </li>\n</ul>\n\n<p>Additionally use the the <a href=\"https://wordpress.stackexchange.com/search?q=\">search</a> on here, because there are already similar Q&amp;A's, which will definitely help you.</p>\n\n<p>Last note, doing such things manually can be painfully time consuming, so I would opt for automating it, of course at the end it is probably an assessment between investing time/money now and the later benefits - here you just have to decide.</p>\n" }, { "answer_id": 179386, "author": "Brian Miksic", "author_id": 68103, "author_profile": "https://wordpress.stackexchange.com/users/68103", "pm_score": 3, "selected": true, "text": "<p>I just completed something like this (with great help from folks on this site).</p>\n\n<p>First, you need to add the rewrite endpoint to your functions:</p>\n\n<pre><code>function wpa_read_endpoint(){\n add_rewrite_endpoint( 'sub-url', EP_PERMALINK);\n}\n\nadd_action( 'init', 'wpa_read_endpoint' );\n</code></pre>\n\n<p>Make sure to then go to the permalinks section of admin and save to refresh permalink settings.</p>\n\n<p>Then add some code to do some template switching dependent on query vars:</p>\n\n<pre><code>function wpa_read_template( $template = '' ) {\n global $wp_query;\n if( ! array_key_exists( 'sub-url', $wp_query-&gt;query_vars ) ) return $template;\n\n $template = locate_template( 'templateFile.php' );\n return $template;\n}\nadd_filter( 'single_template', 'wpa_read_template' );\n</code></pre>\n\n<p>A couple notes:</p>\n\n<ul>\n<li>Refer to add_rewrite_endpoint info for different 'places' (in this case 'EP_Permalink'), I was doing pages so it needed to change. (<a href=\"http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint</a>)</li>\n<li>Any changes you make to the add_rewrite_endpoint code will need to be refreshed by going back to the permalinks section in Admin.</li>\n<li>When adding the template filter (add_filter) make sure you note the correct template 'type', in this case, single_template. Again I was using pages so it was page_template. </li>\n</ul>\n\n<p>Good luck!</p>\n" } ]
2015/02/25
[ "https://wordpress.stackexchange.com/questions/179370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65042/" ]
How can I have a post (or custom post) with a definite URL: ``` www.test.com/category/post-name ``` and a child-URL referring to a specific section of that post ``` www.test.com/category/post-name/sub-url ``` without being obliged to create a specific post related to that child-URL? I have a post with the URL ``` www.test.com/category/post-name ``` originated by file `content-product.php` and I want to have a child-URL like ``` www.test.com/category/post-name/details ``` originated by file `content-product-details.php` that refers/recall only a section/portion of the post. In few words is there a way to create the structure indicated? Or do I have to manually create for each post as many sub-post as child-URL I want to have?
I just completed something like this (with great help from folks on this site). First, you need to add the rewrite endpoint to your functions: ``` function wpa_read_endpoint(){ add_rewrite_endpoint( 'sub-url', EP_PERMALINK); } add_action( 'init', 'wpa_read_endpoint' ); ``` Make sure to then go to the permalinks section of admin and save to refresh permalink settings. Then add some code to do some template switching dependent on query vars: ``` function wpa_read_template( $template = '' ) { global $wp_query; if( ! array_key_exists( 'sub-url', $wp_query->query_vars ) ) return $template; $template = locate_template( 'templateFile.php' ); return $template; } add_filter( 'single_template', 'wpa_read_template' ); ``` A couple notes: * Refer to add\_rewrite\_endpoint info for different 'places' (in this case 'EP\_Permalink'), I was doing pages so it needed to change. (<http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint>) * Any changes you make to the add\_rewrite\_endpoint code will need to be refreshed by going back to the permalinks section in Admin. * When adding the template filter (add\_filter) make sure you note the correct template 'type', in this case, single\_template. Again I was using pages so it was page\_template. Good luck!
179,393
<p>I'm running a 4.1.1 Wordpress without plugins and while trying to upload an image (2mb in this exemplary case) I get:</p> <pre><code> 'http error' </code></pre> <p>when I retry it returns </p> <blockquote> <p>has failed to upload due to an error File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini. ' </p> </blockquote> <p>I have googled (of course) and checked my <code>php.ini</code> settings using <code>phpinfo</code> inside the <code>/wp-content</code> directory.</p> <pre><code> file_uploads on memory_limit 128M upload_max_file_size 25M post_max_size 25M </code></pre> <p>The permissions on <code>/wp-content</code> as well as <code>/wp-content/uploads</code> are in order. the <code>tmp</code> directory is writable and the disk is not full.</p> <p>I have walked through these 2 questions arlready: </p> <ul> <li><a href="https://stackoverflow.com/questions/22462088/wordpress-file-upload-always-give-php-ini-error-updated">WordPress File Upload always give PHP.ini error (Updated)</a></li> <li><a href="https://stackoverflow.com/questions/9115556/error-file-is-empty-when-uploading-images-in-wordpress">Error “file is empty” when uploading images in WordPress</a></li> </ul> <p>Not going to mention all Wordpress forum posts and not running on bluehost or anything like that. Running on my own iron box (Debian)</p> <p>Any clues?</p>
[ { "answer_id": 179381, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>I'd say what you need to look deeper into is the <em>Rewrite API</em> and <em>Endpoints</em>, for starters see:</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints-api/\" rel=\"nofollow noreferrer\">Make WordPress: Rewrite endpoints API</a> </li>\n<li><a href=\"http://codex.wordpress.org/Rewrite_API\" rel=\"nofollow noreferrer\">Codex: Rewrite API</a> </li>\n<li><a href=\"http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow noreferrer\">Codex: Rewrite API/add rewrite endpoint</a> </li>\n</ul>\n\n<p>Additionally use the the <a href=\"https://wordpress.stackexchange.com/search?q=\">search</a> on here, because there are already similar Q&amp;A's, which will definitely help you.</p>\n\n<p>Last note, doing such things manually can be painfully time consuming, so I would opt for automating it, of course at the end it is probably an assessment between investing time/money now and the later benefits - here you just have to decide.</p>\n" }, { "answer_id": 179386, "author": "Brian Miksic", "author_id": 68103, "author_profile": "https://wordpress.stackexchange.com/users/68103", "pm_score": 3, "selected": true, "text": "<p>I just completed something like this (with great help from folks on this site).</p>\n\n<p>First, you need to add the rewrite endpoint to your functions:</p>\n\n<pre><code>function wpa_read_endpoint(){\n add_rewrite_endpoint( 'sub-url', EP_PERMALINK);\n}\n\nadd_action( 'init', 'wpa_read_endpoint' );\n</code></pre>\n\n<p>Make sure to then go to the permalinks section of admin and save to refresh permalink settings.</p>\n\n<p>Then add some code to do some template switching dependent on query vars:</p>\n\n<pre><code>function wpa_read_template( $template = '' ) {\n global $wp_query;\n if( ! array_key_exists( 'sub-url', $wp_query-&gt;query_vars ) ) return $template;\n\n $template = locate_template( 'templateFile.php' );\n return $template;\n}\nadd_filter( 'single_template', 'wpa_read_template' );\n</code></pre>\n\n<p>A couple notes:</p>\n\n<ul>\n<li>Refer to add_rewrite_endpoint info for different 'places' (in this case 'EP_Permalink'), I was doing pages so it needed to change. (<a href=\"http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint</a>)</li>\n<li>Any changes you make to the add_rewrite_endpoint code will need to be refreshed by going back to the permalinks section in Admin.</li>\n<li>When adding the template filter (add_filter) make sure you note the correct template 'type', in this case, single_template. Again I was using pages so it was page_template. </li>\n</ul>\n\n<p>Good luck!</p>\n" } ]
2015/02/25
[ "https://wordpress.stackexchange.com/questions/179393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68169/" ]
I'm running a 4.1.1 Wordpress without plugins and while trying to upload an image (2mb in this exemplary case) I get: ``` 'http error' ``` when I retry it returns > > has failed to upload due to an error > File is empty. Please upload something more substantial. This error could > also be caused by uploads being disabled in your php.ini or by > post\_max\_size being defined as smaller than upload\_max\_filesize in php.ini. ' > > > I have googled (of course) and checked my `php.ini` settings using `phpinfo` inside the `/wp-content` directory. ``` file_uploads on memory_limit 128M upload_max_file_size 25M post_max_size 25M ``` The permissions on `/wp-content` as well as `/wp-content/uploads` are in order. the `tmp` directory is writable and the disk is not full. I have walked through these 2 questions arlready: * [WordPress File Upload always give PHP.ini error (Updated)](https://stackoverflow.com/questions/22462088/wordpress-file-upload-always-give-php-ini-error-updated) * [Error “file is empty” when uploading images in WordPress](https://stackoverflow.com/questions/9115556/error-file-is-empty-when-uploading-images-in-wordpress) Not going to mention all Wordpress forum posts and not running on bluehost or anything like that. Running on my own iron box (Debian) Any clues?
I just completed something like this (with great help from folks on this site). First, you need to add the rewrite endpoint to your functions: ``` function wpa_read_endpoint(){ add_rewrite_endpoint( 'sub-url', EP_PERMALINK); } add_action( 'init', 'wpa_read_endpoint' ); ``` Make sure to then go to the permalinks section of admin and save to refresh permalink settings. Then add some code to do some template switching dependent on query vars: ``` function wpa_read_template( $template = '' ) { global $wp_query; if( ! array_key_exists( 'sub-url', $wp_query->query_vars ) ) return $template; $template = locate_template( 'templateFile.php' ); return $template; } add_filter( 'single_template', 'wpa_read_template' ); ``` A couple notes: * Refer to add\_rewrite\_endpoint info for different 'places' (in this case 'EP\_Permalink'), I was doing pages so it needed to change. (<http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint>) * Any changes you make to the add\_rewrite\_endpoint code will need to be refreshed by going back to the permalinks section in Admin. * When adding the template filter (add\_filter) make sure you note the correct template 'type', in this case, single\_template. Again I was using pages so it was page\_template. Good luck!
179,400
<p>I write code to save data in to the database table.</p> <p>I want Replace a row in a table if it exists or insert a new row in a table if the row did not already exist.</p> <p><a href="http://codex.wordpress.org/Class_Reference/wpdb" rel="nofollow">http://codex.wordpress.org/Class_Reference/wpdb</a></p> <p>I use <code>$wpdb-&gt;replace</code> function and then add <code>$wpdb-&gt;insert</code>_id to end of code.</p> <p>For Update all fields , I using replace 'id' That is primary key.</p> <p>I add the id field to array </p> <pre><code> $wpdb-&gt;replace( $wpdb-&gt;prefix . 'fafa', array( 'id', 'title' =&gt; trim($row-&gt;item(0)-&gt;nodeValue) , 'liveprice' =&gt; trim($row-&gt;item(2)-&gt;nodeValue) , 'changing' =&gt; trim($row-&gt;item(4)-&gt;nodeValue) , 'lowest' =&gt; trim($row-&gt;item(6)-&gt;nodeValue) , 'topest' =&gt; trim($row-&gt;item(8)-&gt;nodeValue) , 'time' =&gt; trim($row-&gt;item(10)-&gt;nodeValue) ), array( '%d', '%s', '%s', '%s', '%s', '%s', '%s' ) ); $wpdb-&gt;insert_Id; </code></pre>
[ { "answer_id": 179443, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": false, "text": "<p><code>replace</code> will only replace a row if one of the column values you supply is a <code>primary key</code> or <code>unique</code> index, and that value is identical to an existing row. If your table has neither a <code>primary key</code> or <code>unique</code> index, it will always only insert new rows. You will have to first query for existing data to decide if something should be deleted and a new row inserted.</p>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/replace.html\" rel=\"noreferrer\"><code>REPLACE</code></a> in MySQL documentation for more information.</p>\n" }, { "answer_id": 179773, "author": "amir rasabeh", "author_id": 67818, "author_profile": "https://wordpress.stackexchange.com/users/67818", "pm_score": 3, "selected": true, "text": "<p>You Can use This solution..</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/125380/how-to-delete-all-records-from-or-empty-a-custom-database-table\">How to delete all records from or empty a custom database table?</a></p>\n\n<p>In this solution First delete all records an then insert new records</p>\n\n<p>(your table should be have records before to delete query because If run $delete you give error 'No find row' ) and No need to use <code>replace</code> I us <code>insert</code></p>\n\n<p>add this following query before your function. (this query delete all records )</p>\n\n<pre><code>$delete = $wpdb-&gt;query(\"TRUNCATE TABLE `wp_table_name`\");\n\n\n\n\n$delete = $wpdb-&gt;query(\"TRUNCATE TABLE `wp_table_name`\"); /// delete all records\n\n $wpdb-&gt;insert( $wpdb-&gt;prefix . 'fafa', \n array( \n 'title' =&gt; trim($row-&gt;item(0)-&gt;nodeValue) ,\n 'liveprice' =&gt; trim($row-&gt;item(2)-&gt;nodeValue) ,\n 'changing' =&gt; trim($row-&gt;item(4)-&gt;nodeValue) ,\n 'lowest' =&gt; trim($row-&gt;item(6)-&gt;nodeValue) ,\n 'topest' =&gt; trim($row-&gt;item(8)-&gt;nodeValue) ,\n 'time' =&gt; trim($row-&gt;item(10)-&gt;nodeValue) ), \n array( \n '%s',\n '%s',\n '%s',\n '%s',\n '%s',\n '%s'\n) );\n</code></pre>\n\n<p>run foreach</p>\n\n<p><strong>Note</strong>: If your code is in a loop you should insert this query before loop.</p>\n\n<pre><code> $delete = $wpdb-&gt;query(\"TRUNCATE TABLE `wp_table_name`\");\n foreach (){\n\n// code\n\n }\n</code></pre>\n" }, { "answer_id": 300479, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 2, "selected": false, "text": "<p>The responses to this question do not give a clear answer and I cannot see how the chosen answer is correct because the question does not say anything about deleting all the rows in the table and there can be no need to TRUNCATE the table in order to replace the values in a row. So here is an answer albeit a bit late:</p>\n\n<p>If you are using the replace() function where there is an id in the replace then it means that the record <strong>may exist</strong> in the first place otherwise you would always go straight to the insert() function to add a new record. Therefore there must be some field other than the primary key (id) that defines whether the record exists or not. In the above example lets assume that the title is the important field that defines whether a new record is needed or the fields in a record need to be updated.</p>\n\n<p>I always to use the get_var() function with the replace() function as follows:</p>\n\n<p>First check if the record exists (for the important field) so that the id can be passed on to the replace function as follows:</p>\n\n<pre><code>$recID = $wpdb-&gt;get_var( \"SELECT id FROM \".($wpdb-&gt;prefix . 'fafa').\" WHERE title LIKE \".$title.\"'\");\n</code></pre>\n\n<p>Now use the replace function that will create a new record or update the fields for the $recID found:</p>\n\n<pre><code>$wpdb-&gt;replace( $wpdb-&gt;prefix . 'fafa', \n array( \n 'id' =&gt; $recID,\n 'title' =&gt; trim($row-&gt;item(0)-&gt;nodeValue) ,\n 'liveprice' =&gt; trim($row-&gt;item(2)-&gt;nodeValue) ,\n 'changing' =&gt; trim($row-&gt;item(4)-&gt;nodeValue) ,\n 'lowest' =&gt; trim($row-&gt;item(6)-&gt;nodeValue) ,\n 'topest' =&gt; trim($row-&gt;item(8)-&gt;nodeValue) ,\n 'time' =&gt; trim($row-&gt;item(10)-&gt;nodeValue) ), \n array(\n '%d', '%s', '%s', '%s', '%s', '%s', '%s' )\n);\n</code></pre>\n\n<p>Finally, after replace, the ID generated from the AUTO_INCREMENT column can be accessed using:</p>\n\n<pre><code>$wpdb-&gt;insert_id;\n</code></pre>\n\n<p>I hope that this helps someone who has a similar question to the original.</p>\n" } ]
2015/02/25
[ "https://wordpress.stackexchange.com/questions/179400", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48589/" ]
I write code to save data in to the database table. I want Replace a row in a table if it exists or insert a new row in a table if the row did not already exist. <http://codex.wordpress.org/Class_Reference/wpdb> I use `$wpdb->replace` function and then add `$wpdb->insert`\_id to end of code. For Update all fields , I using replace 'id' That is primary key. I add the id field to array ``` $wpdb->replace( $wpdb->prefix . 'fafa', array( 'id', 'title' => trim($row->item(0)->nodeValue) , 'liveprice' => trim($row->item(2)->nodeValue) , 'changing' => trim($row->item(4)->nodeValue) , 'lowest' => trim($row->item(6)->nodeValue) , 'topest' => trim($row->item(8)->nodeValue) , 'time' => trim($row->item(10)->nodeValue) ), array( '%d', '%s', '%s', '%s', '%s', '%s', '%s' ) ); $wpdb->insert_Id; ```
You Can use This solution.. [How to delete all records from or empty a custom database table?](https://wordpress.stackexchange.com/questions/125380/how-to-delete-all-records-from-or-empty-a-custom-database-table) In this solution First delete all records an then insert new records (your table should be have records before to delete query because If run $delete you give error 'No find row' ) and No need to use `replace` I us `insert` add this following query before your function. (this query delete all records ) ``` $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); /// delete all records $wpdb->insert( $wpdb->prefix . 'fafa', array( 'title' => trim($row->item(0)->nodeValue) , 'liveprice' => trim($row->item(2)->nodeValue) , 'changing' => trim($row->item(4)->nodeValue) , 'lowest' => trim($row->item(6)->nodeValue) , 'topest' => trim($row->item(8)->nodeValue) , 'time' => trim($row->item(10)->nodeValue) ), array( '%s', '%s', '%s', '%s', '%s', '%s' ) ); ``` run foreach **Note**: If your code is in a loop you should insert this query before loop. ``` $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); foreach (){ // code } ```
179,448
<p>This one has been bothering me for a few days now, so I'd really appreciate any help you can give me.</p> <p><strong>Problem overview:</strong></p> <p>I have a plugin which automatically creates a post and assigns the category "YouTube" whenever a new video is uploaded to a YouTube channel. This part works fine. However - I'm also wanting the post to be assigned the post type "Video". The plugin doesn't allow for this type of customisation, so this will have to be done in php.</p> <p><strong>Where I've looked:</strong> (included for those who like to say "Have you read the forums?")</p> <p><a href="http://codex.wordpress.org/Function_Reference/set_post_format" rel="nofollow noreferrer">WordPress Codex Set Post Format</a></p> <p><a href="http://codex.wordpress.org/Template_Tags/in_category" rel="nofollow noreferrer">WordPress Codex In Category</a></p> <p><a href="https://wordpress.stackexchange.com/questions/26416/add-category-to-custom-post-type-automatically-using-category-slug">WordPress Stack Exchange 1</a></p> <p><a href="https://wordpress.stackexchange.com/questions/8217/anyway-to-assign-custom-post-types-to-a-specific-category">WordPress Stack Exchange 2</a></p> <p><strong>What I've tried:</strong></p> <p>A few different attempts aren't getting me any results (not white screen of deathing me either so that's a bonus?)</p> <p>1: (not sure where I'd need to tell that function to run)</p> <pre><code>//* If post has category YouTube - set post type to video function default_post_type($post_id) { // check autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; if (in_category('YouTube')) { set_post_format($post_id, 'video'); } } } </code></pre> <p>2: (mixing it up a little bit, because ... reasons?)</p> <pre><code>//* If post has category YouTube - set post type to video // check autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; function default_post_type($post_id) { if (in_category('YouTube')) { set_post_format($post_id, 'video'); } } } </code></pre> <p>3: (so then I thought "Why even use a function at all?")</p> <pre><code>//* If post has category YouTube - set post type to video if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; if (in_category('YouTube', $post_id)) { set_post_format($post_id, 'video'); } } </code></pre> <p>Appreciate any help - even if you can tell me why what I've done is wrong. Thanks.</p>
[ { "answer_id": 179443, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": false, "text": "<p><code>replace</code> will only replace a row if one of the column values you supply is a <code>primary key</code> or <code>unique</code> index, and that value is identical to an existing row. If your table has neither a <code>primary key</code> or <code>unique</code> index, it will always only insert new rows. You will have to first query for existing data to decide if something should be deleted and a new row inserted.</p>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/replace.html\" rel=\"noreferrer\"><code>REPLACE</code></a> in MySQL documentation for more information.</p>\n" }, { "answer_id": 179773, "author": "amir rasabeh", "author_id": 67818, "author_profile": "https://wordpress.stackexchange.com/users/67818", "pm_score": 3, "selected": true, "text": "<p>You Can use This solution..</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/125380/how-to-delete-all-records-from-or-empty-a-custom-database-table\">How to delete all records from or empty a custom database table?</a></p>\n\n<p>In this solution First delete all records an then insert new records</p>\n\n<p>(your table should be have records before to delete query because If run $delete you give error 'No find row' ) and No need to use <code>replace</code> I us <code>insert</code></p>\n\n<p>add this following query before your function. (this query delete all records )</p>\n\n<pre><code>$delete = $wpdb-&gt;query(\"TRUNCATE TABLE `wp_table_name`\");\n\n\n\n\n$delete = $wpdb-&gt;query(\"TRUNCATE TABLE `wp_table_name`\"); /// delete all records\n\n $wpdb-&gt;insert( $wpdb-&gt;prefix . 'fafa', \n array( \n 'title' =&gt; trim($row-&gt;item(0)-&gt;nodeValue) ,\n 'liveprice' =&gt; trim($row-&gt;item(2)-&gt;nodeValue) ,\n 'changing' =&gt; trim($row-&gt;item(4)-&gt;nodeValue) ,\n 'lowest' =&gt; trim($row-&gt;item(6)-&gt;nodeValue) ,\n 'topest' =&gt; trim($row-&gt;item(8)-&gt;nodeValue) ,\n 'time' =&gt; trim($row-&gt;item(10)-&gt;nodeValue) ), \n array( \n '%s',\n '%s',\n '%s',\n '%s',\n '%s',\n '%s'\n) );\n</code></pre>\n\n<p>run foreach</p>\n\n<p><strong>Note</strong>: If your code is in a loop you should insert this query before loop.</p>\n\n<pre><code> $delete = $wpdb-&gt;query(\"TRUNCATE TABLE `wp_table_name`\");\n foreach (){\n\n// code\n\n }\n</code></pre>\n" }, { "answer_id": 300479, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 2, "selected": false, "text": "<p>The responses to this question do not give a clear answer and I cannot see how the chosen answer is correct because the question does not say anything about deleting all the rows in the table and there can be no need to TRUNCATE the table in order to replace the values in a row. So here is an answer albeit a bit late:</p>\n\n<p>If you are using the replace() function where there is an id in the replace then it means that the record <strong>may exist</strong> in the first place otherwise you would always go straight to the insert() function to add a new record. Therefore there must be some field other than the primary key (id) that defines whether the record exists or not. In the above example lets assume that the title is the important field that defines whether a new record is needed or the fields in a record need to be updated.</p>\n\n<p>I always to use the get_var() function with the replace() function as follows:</p>\n\n<p>First check if the record exists (for the important field) so that the id can be passed on to the replace function as follows:</p>\n\n<pre><code>$recID = $wpdb-&gt;get_var( \"SELECT id FROM \".($wpdb-&gt;prefix . 'fafa').\" WHERE title LIKE \".$title.\"'\");\n</code></pre>\n\n<p>Now use the replace function that will create a new record or update the fields for the $recID found:</p>\n\n<pre><code>$wpdb-&gt;replace( $wpdb-&gt;prefix . 'fafa', \n array( \n 'id' =&gt; $recID,\n 'title' =&gt; trim($row-&gt;item(0)-&gt;nodeValue) ,\n 'liveprice' =&gt; trim($row-&gt;item(2)-&gt;nodeValue) ,\n 'changing' =&gt; trim($row-&gt;item(4)-&gt;nodeValue) ,\n 'lowest' =&gt; trim($row-&gt;item(6)-&gt;nodeValue) ,\n 'topest' =&gt; trim($row-&gt;item(8)-&gt;nodeValue) ,\n 'time' =&gt; trim($row-&gt;item(10)-&gt;nodeValue) ), \n array(\n '%d', '%s', '%s', '%s', '%s', '%s', '%s' )\n);\n</code></pre>\n\n<p>Finally, after replace, the ID generated from the AUTO_INCREMENT column can be accessed using:</p>\n\n<pre><code>$wpdb-&gt;insert_id;\n</code></pre>\n\n<p>I hope that this helps someone who has a similar question to the original.</p>\n" } ]
2015/02/26
[ "https://wordpress.stackexchange.com/questions/179448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51266/" ]
This one has been bothering me for a few days now, so I'd really appreciate any help you can give me. **Problem overview:** I have a plugin which automatically creates a post and assigns the category "YouTube" whenever a new video is uploaded to a YouTube channel. This part works fine. However - I'm also wanting the post to be assigned the post type "Video". The plugin doesn't allow for this type of customisation, so this will have to be done in php. **Where I've looked:** (included for those who like to say "Have you read the forums?") [WordPress Codex Set Post Format](http://codex.wordpress.org/Function_Reference/set_post_format) [WordPress Codex In Category](http://codex.wordpress.org/Template_Tags/in_category) [WordPress Stack Exchange 1](https://wordpress.stackexchange.com/questions/26416/add-category-to-custom-post-type-automatically-using-category-slug) [WordPress Stack Exchange 2](https://wordpress.stackexchange.com/questions/8217/anyway-to-assign-custom-post-types-to-a-specific-category) **What I've tried:** A few different attempts aren't getting me any results (not white screen of deathing me either so that's a bonus?) 1: (not sure where I'd need to tell that function to run) ``` //* If post has category YouTube - set post type to video function default_post_type($post_id) { // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; if (in_category('YouTube')) { set_post_format($post_id, 'video'); } } } ``` 2: (mixing it up a little bit, because ... reasons?) ``` //* If post has category YouTube - set post type to video // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; function default_post_type($post_id) { if (in_category('YouTube')) { set_post_format($post_id, 'video'); } } } ``` 3: (so then I thought "Why even use a function at all?") ``` //* If post has category YouTube - set post type to video if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; if (in_category('YouTube', $post_id)) { set_post_format($post_id, 'video'); } } ``` Appreciate any help - even if you can tell me why what I've done is wrong. Thanks.
You Can use This solution.. [How to delete all records from or empty a custom database table?](https://wordpress.stackexchange.com/questions/125380/how-to-delete-all-records-from-or-empty-a-custom-database-table) In this solution First delete all records an then insert new records (your table should be have records before to delete query because If run $delete you give error 'No find row' ) and No need to use `replace` I us `insert` add this following query before your function. (this query delete all records ) ``` $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); /// delete all records $wpdb->insert( $wpdb->prefix . 'fafa', array( 'title' => trim($row->item(0)->nodeValue) , 'liveprice' => trim($row->item(2)->nodeValue) , 'changing' => trim($row->item(4)->nodeValue) , 'lowest' => trim($row->item(6)->nodeValue) , 'topest' => trim($row->item(8)->nodeValue) , 'time' => trim($row->item(10)->nodeValue) ), array( '%s', '%s', '%s', '%s', '%s', '%s' ) ); ``` run foreach **Note**: If your code is in a loop you should insert this query before loop. ``` $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`"); foreach (){ // code } ```
179,484
<p>I'm trying to display all the categories that belong to the custom post type that the user is in.</p> <p>For example this post: <a href="http://bit.ly/1ANisxN" rel="nofollow noreferrer">http://bit.ly/1ANisxN</a> Is a custom post type that belongs to this page category: <a href="http://bit.ly/1FYscKh" rel="nofollow noreferrer">http://bit.ly/1FYscKh</a></p> <p>As you can see the page category shows it's child categories which is exactly what I want to achieve it the custom post: i.imgur.com/vk4K31T.png</p> <p>This is the things I have tried in the custom post to show the parent categories with no luck:</p> <pre><code>&lt;?php echo get_category_parents() ?&gt; </code></pre> <p>By the way, this is how the category page is echoing its subcategories: </p> <pre><code>&lt;?php $terms = get_terms( 'btp_work_category' ); foreach ( $terms as $term ) { ?&gt; &lt;li&gt;&lt;a href="#" data-filter=".filter-&lt;?php echo $term-&gt;term_id; ?&gt;"&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt; </code></pre> <p>Any idea on how to do this?</p> <p>For example this category structure:</p> <p>Electronics (Top category)</p> <ul> <li><p>Cameras (sub category)</p> <ul> <li>posts</li> </ul></li> <li><p>TV (sub category)</p> <ul> <li>posts</li> </ul></li> <li><p>Cellphones (sub category)</p> <ul> <li>posts</li> </ul></li> </ul> <p>So If I'm on a <code>cameras</code> post I want to display the top category of it and its subcategories (which are relative to <code>cameras</code> since all are under `Electronics')</p>
[ { "answer_id": 179494, "author": "Przemek Maczewski", "author_id": 68013, "author_profile": "https://wordpress.stackexchange.com/users/68013", "pm_score": 2, "selected": true, "text": "<p>If you're in the single custom post template, you can get the terms that the post belongs to by use of</p>\n\n<pre><code>$terms = get_the_terms( get_the_ID(), 'btp_work_category' );\n</code></pre>\n\n<p>Then you need to determine parent term and display it with its children.</p>\n\n<p>The code below assumes that the post belongs to one top category (term) and the taxonomy tree has no more than 2 levels.</p>\n\n<pre><code>$terms = get_the_terms( get_the_ID(), 'btp_work_category' );\nif ( ! empty( $terms ) ) :\n echo \"&lt;ul&gt;\\n\";\n // Parent term detection and display\n $term = array_pop( $terms );\n $parent_term = ( $term-&gt;parent ? get_term( $term-&gt;parent, 'btp_work_category' ) : $term );\n echo \"&lt;li&gt;\\n\";\n echo '&lt;a href=\"' . get_term_link( $parent_term, 'btp_work_category' ) . '\"&gt;' . $parent_term-&gt;name . '&lt;/a&gt;';\n // Getting children\n $child_terms = get_term_children( $parent_term-&gt;term_id, 'btp_work_category' );\n if ( ! empty( $child_terms ) ) :\n echo \"\\n&lt;ul&gt;\\n\";\n foreach ( $child_terms as $child_term_id ) :\n $child_term = get_term_by( 'id', $child_term_id, 'btp_work_category' );\n echo '&lt;li&gt;&lt;a href=\"' . get_term_link( $child_term, 'btp_work_category' ) . '\"&gt;' . $child_term-&gt;name . \"&lt;/a&gt;&lt;/li&gt;\\n\";\n endforeach;\n echo \"&lt;/ul&gt;\\n\";\n endif; // ( ! empty( $child_terms ) )\n echo \"&lt;/li&gt;\\n\";\n echo \"&lt;/ul&gt;\\n\";\nendif; // ( ! empty( $terms ) )\n</code></pre>\n" }, { "answer_id": 182549, "author": "Dameer", "author_id": 13076, "author_profile": "https://wordpress.stackexchange.com/users/13076", "pm_score": 0, "selected": false, "text": "<p>Here's something that should kinda work... in spite of the fact that CPTs don't have a parent category as regular WP posts do.</p>\n\n<pre><code>function get_cpt_parent_cat_aka_taxonomy() {\n global $post;\n $parent_tax_name = 'Undefined parent taxonomy!';\n $obj_taxonomies = get_object_taxonomies( $post-&gt;post_type, 'objects' );\n $slugs = array();\n if( !empty( $obj_taxonomies ) ) {\n foreach ( $obj_taxonomies as $key =&gt; $tax ) {\n if( $tax-&gt;show_ui === true &amp;&amp; $tax-&gt;public === true &amp;&amp; $tax-&gt;hierarchical !== false ) {\n array_push( $slugs, $tax-&gt;name );\n }\n }\n $terms = wp_get_post_terms( $post-&gt;ID, $slugs );\n $term = get_term( $terms[ 0 ]-&gt;term_id, $terms[ 0 ]-&gt;taxonomy );\n $parent_tax_name = $term-&gt;name;\n }\n return $parent_tax_name;\n}\n</code></pre>\n" } ]
2015/02/26
[ "https://wordpress.stackexchange.com/questions/179484", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68230/" ]
I'm trying to display all the categories that belong to the custom post type that the user is in. For example this post: <http://bit.ly/1ANisxN> Is a custom post type that belongs to this page category: <http://bit.ly/1FYscKh> As you can see the page category shows it's child categories which is exactly what I want to achieve it the custom post: i.imgur.com/vk4K31T.png This is the things I have tried in the custom post to show the parent categories with no luck: ``` <?php echo get_category_parents() ?> ``` By the way, this is how the category page is echoing its subcategories: ``` <?php $terms = get_terms( 'btp_work_category' ); foreach ( $terms as $term ) { ?> <li><a href="#" data-filter=".filter-<?php echo $term->term_id; ?>"><?php echo $term->name; ?></a></li> <?php } ?> ``` Any idea on how to do this? For example this category structure: Electronics (Top category) * Cameras (sub category) + posts * TV (sub category) + posts * Cellphones (sub category) + posts So If I'm on a `cameras` post I want to display the top category of it and its subcategories (which are relative to `cameras` since all are under `Electronics')
If you're in the single custom post template, you can get the terms that the post belongs to by use of ``` $terms = get_the_terms( get_the_ID(), 'btp_work_category' ); ``` Then you need to determine parent term and display it with its children. The code below assumes that the post belongs to one top category (term) and the taxonomy tree has no more than 2 levels. ``` $terms = get_the_terms( get_the_ID(), 'btp_work_category' ); if ( ! empty( $terms ) ) : echo "<ul>\n"; // Parent term detection and display $term = array_pop( $terms ); $parent_term = ( $term->parent ? get_term( $term->parent, 'btp_work_category' ) : $term ); echo "<li>\n"; echo '<a href="' . get_term_link( $parent_term, 'btp_work_category' ) . '">' . $parent_term->name . '</a>'; // Getting children $child_terms = get_term_children( $parent_term->term_id, 'btp_work_category' ); if ( ! empty( $child_terms ) ) : echo "\n<ul>\n"; foreach ( $child_terms as $child_term_id ) : $child_term = get_term_by( 'id', $child_term_id, 'btp_work_category' ); echo '<li><a href="' . get_term_link( $child_term, 'btp_work_category' ) . '">' . $child_term->name . "</a></li>\n"; endforeach; echo "</ul>\n"; endif; // ( ! empty( $child_terms ) ) echo "</li>\n"; echo "</ul>\n"; endif; // ( ! empty( $terms ) ) ```
179,527
<p>Firstly this is neither an SEO question nor a question about changing the title tag sitewide. If you google my question those are all the answers you see.</p> <p>So we have our own theme and we have complete control over header.php. We know how to set the title. Currently it looks like this:</p> <pre><code>&lt;head&gt; &lt;title&gt;&lt;?php wp_title(' | ', true, 'right'); bloginfo('name'); ?&gt;&lt;/title&gt; etc... </code></pre> <p>Nope, the problem is this. For most pages we <em>want</em> the title to show as above. It's just that we've realised that for one particular custom post type (and its associated template) the CPT's title shouldn't appear publicly. It's for admin use only. Strange, but there you go. We don't show it anywhere in the template's H1, content, etc. </p> <p>But it is showing in the title.</p> <p>Ideally we'd like a way to override the header.php title from within the template, to specify an alternative title just for this particular set of pages. Is that possible?</p>
[ { "answer_id": 179532, "author": "Przemek Maczewski", "author_id": 68013, "author_profile": "https://wordpress.stackexchange.com/users/68013", "pm_score": 2, "selected": false, "text": "<p>You may want to filter out the title.</p>\n\n<pre><code>add_filter( 'wp_title', 'wpse179527_wp_title' );\nfunction wpse179527_wp_title( $title ) {\n global $post;\n if ( is_single() &amp;&amp; 'custom-post' == get_post_type( $post ) )\n return '';\n return $title;\n}\n</code></pre>\n" }, { "answer_id": 179536, "author": "Shawn Wernig", "author_id": 16368, "author_profile": "https://wordpress.stackexchange.com/users/16368", "pm_score": 3, "selected": true, "text": "<p>First, let's change your <code>&lt;title&gt;</code> to</p>\n\n<pre><code>&lt;title&gt;&lt;?php wp_title(' | ', true, 'right'); ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>Because adding to the title string in that was isn't very future-forward, instead it's best to use a filter to do any modifications to the title. So let's instead ad (in functions.php):</p>\n\n<pre><code>add_filter('wp_title', 'my_custom_title');\nfunction my_custom_title( $title )\n{\n // Return my custom title\n return sprintf(\"%s %s\", $title, get_bloginfo('name'));\n}\n</code></pre>\n\n<p>Then let's extend this handy little title filter to do what you're wanting to do:</p>\n\n<pre><code>add_filter('wp_title', 'my_custom_title');\nfunction my_custom_title( $title )\n{\n if( is_singular(\"your_post_type\"))\n {\n return \"\"; // Return empty\n }\n // Return my custom title\n return sprintf(\"%s %s\", $title, get_bloginfo('name'));\n}\n</code></pre>\n" }, { "answer_id": 369136, "author": "SnnSnn", "author_id": 165241, "author_profile": "https://wordpress.stackexchange.com/users/165241", "pm_score": 2, "selected": false, "text": "<p>I posted this answer for another question but since it is relevant and more up-to-date, I though it might be useful for some people.</p>\n<p>How document title is generated has changed since Wordpress v4.4.0. Now <code>wp_get_document_title</code> dictates how title is generated:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Displays title tag with content.\n *\n * @ignore\n * @since 4.1.0\n * @since 4.4.0 Improved title output replaced `wp_title()`.\n * @access private\n */\nfunction _wp_render_title_tag() {\n if ( ! current_theme_supports( 'title-tag' ) ) {\n return;\n }\n\n echo '&lt;title&gt;' . wp_get_document_title() . '&lt;/title&gt;' . &quot;\\n&quot;;\n}\n</code></pre>\n<p>Here is the code from v5.4.2. Here are the filters you can use to manipulate title tag:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wp_get_document_title() {\n /**\n * Filters the document title before it is generated.\n *\n * Passing a non-empty value will short-circuit wp_get_document_title(),\n * returning that value instead.\n *\n * @since 4.4.0\n *\n * @param string $title The document title. Default empty string.\n */\n $title = apply_filters( 'pre_get_document_title', '' );\n if ( ! empty( $title ) ) {\n return $title;\n }\n // --- snipped ---\n /**\n * Filters the separator for the document title.\n *\n * @since 4.4.0\n *\n * @param string $sep Document title separator. Default '-'.\n */\n $sep = apply_filters( 'document_title_separator', '-' );\n\n /**\n * Filters the parts of the document title.\n *\n * @since 4.4.0\n *\n * @param array $title {\n * The document title parts.\n *\n * @type string $title Title of the viewed page.\n * @type string $page Optional. Page number if paginated.\n * @type string $tagline Optional. Site description when on home page.\n * @type string $site Optional. Site title when not on home page.\n * }\n */\n $title = apply_filters( 'document_title_parts', $title );\n // --- snipped ---\n return $title;\n}\n</code></pre>\n<p>So here are two ways you can do it.</p>\n<p>First one uses <code>pre_get_document_title</code> filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_document_title( $title ) {\n return 'Here is the new title';\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 10 );\n</code></pre>\n<p>Second way uses <code>document_title_separator</code> and <code>document_title_parts</code> hooks for the title and the title seperator that are executed later in the function, after title is generated using functions like <code>single_term_title</code> or <code>post_type_archive_title</code> depending on the page and about to be outputted:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Custom function should return a string\nfunction custom_seperator( $sep ) {\n return '&gt;';\n}\nadd_filter( 'document_title_separator', 'custom_seperator', 10 );\n\n// Custom function should return an array\nfunction custom_html_title( $title ) {\n return array(\n 'title' =&gt; 'Custom Title',\n 'site' =&gt; 'Custom Site'\n );\n}\nadd_filter( 'document_title_parts', 'custom_html_title', 10 );\n</code></pre>\n" }, { "answer_id": 388573, "author": "Rami Alloush", "author_id": 146507, "author_profile": "https://wordpress.stackexchange.com/users/146507", "pm_score": 1, "selected": false, "text": "<p>Combining different answers, this is what worked for me on WordPress <code>v5.7.2</code> and my custom post type <code>company</code>. I was able to easily override the title on custom post page to add my Site Name at the end</p>\n<pre><code>function custom_document_title( $title ) {\n if( is_singular(&quot;company&quot;))\n {\n return sprintf(&quot;%s - %s&quot;, $title, get_bloginfo('name'));\n }\n return $title; // Return default title elsewhere\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 99 );\n</code></pre>\n" }, { "answer_id": 413954, "author": "Slingshot Design", "author_id": 229390, "author_profile": "https://wordpress.stackexchange.com/users/229390", "pm_score": 0, "selected": false, "text": "<p>The previous version didn't work for me in Wordpress 6.1.1 as it returned an empty $title. This version returns the page title + blog name or any custom text you want.</p>\n<pre><code>function custom_document_title( $title ) {\n global $post;\n $title = get_the_title($post);\n if( is_singular(&quot;event&quot;)){\n return sprintf(&quot;%s - %s&quot;, $title, 'Event Registration');\n } else {\n // Return the usual Wordpress style title\n return sprintf(&quot;%s - %s&quot;, $title, get_bloginfo('name'));\n }\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 99 );\n</code></pre>\n" } ]
2015/02/26
[ "https://wordpress.stackexchange.com/questions/179527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/875/" ]
Firstly this is neither an SEO question nor a question about changing the title tag sitewide. If you google my question those are all the answers you see. So we have our own theme and we have complete control over header.php. We know how to set the title. Currently it looks like this: ``` <head> <title><?php wp_title(' | ', true, 'right'); bloginfo('name'); ?></title> etc... ``` Nope, the problem is this. For most pages we *want* the title to show as above. It's just that we've realised that for one particular custom post type (and its associated template) the CPT's title shouldn't appear publicly. It's for admin use only. Strange, but there you go. We don't show it anywhere in the template's H1, content, etc. But it is showing in the title. Ideally we'd like a way to override the header.php title from within the template, to specify an alternative title just for this particular set of pages. Is that possible?
First, let's change your `<title>` to ``` <title><?php wp_title(' | ', true, 'right'); ?></title> ``` Because adding to the title string in that was isn't very future-forward, instead it's best to use a filter to do any modifications to the title. So let's instead ad (in functions.php): ``` add_filter('wp_title', 'my_custom_title'); function my_custom_title( $title ) { // Return my custom title return sprintf("%s %s", $title, get_bloginfo('name')); } ``` Then let's extend this handy little title filter to do what you're wanting to do: ``` add_filter('wp_title', 'my_custom_title'); function my_custom_title( $title ) { if( is_singular("your_post_type")) { return ""; // Return empty } // Return my custom title return sprintf("%s %s", $title, get_bloginfo('name')); } ```
179,548
<p>I am trying to list my news items in 3 columns in a vertical design: image, date, title. I'm having some trouble calling the featured image. Is there a specific function that would help me with this? Also add CSS style to list them in 3 columns? </p> <p>Website Example: <a href="http://www.enterpriseflorida.com/why-florida/infrastructure/" rel="nofollow">http://www.enterpriseflorida.com/why-florida/infrastructure/</a></p> <p>My Code:</p> <pre><code> &lt;?php $posts = get_posts( 'numberposts=2&amp;order=DESC&amp;orderby=post_title&amp;category_name=news' ); foreach ( $posts as $post ) : start_wp(); ?&gt; &lt;?php toolbox_posted_on(); ?&gt; &lt;h4&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title() ; ?&gt;&lt;/a&gt;&lt;/h4&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; &lt;a href="#" class="btn blue"&gt;Read All News&lt;/a&gt; </code></pre>
[ { "answer_id": 179532, "author": "Przemek Maczewski", "author_id": 68013, "author_profile": "https://wordpress.stackexchange.com/users/68013", "pm_score": 2, "selected": false, "text": "<p>You may want to filter out the title.</p>\n\n<pre><code>add_filter( 'wp_title', 'wpse179527_wp_title' );\nfunction wpse179527_wp_title( $title ) {\n global $post;\n if ( is_single() &amp;&amp; 'custom-post' == get_post_type( $post ) )\n return '';\n return $title;\n}\n</code></pre>\n" }, { "answer_id": 179536, "author": "Shawn Wernig", "author_id": 16368, "author_profile": "https://wordpress.stackexchange.com/users/16368", "pm_score": 3, "selected": true, "text": "<p>First, let's change your <code>&lt;title&gt;</code> to</p>\n\n<pre><code>&lt;title&gt;&lt;?php wp_title(' | ', true, 'right'); ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>Because adding to the title string in that was isn't very future-forward, instead it's best to use a filter to do any modifications to the title. So let's instead ad (in functions.php):</p>\n\n<pre><code>add_filter('wp_title', 'my_custom_title');\nfunction my_custom_title( $title )\n{\n // Return my custom title\n return sprintf(\"%s %s\", $title, get_bloginfo('name'));\n}\n</code></pre>\n\n<p>Then let's extend this handy little title filter to do what you're wanting to do:</p>\n\n<pre><code>add_filter('wp_title', 'my_custom_title');\nfunction my_custom_title( $title )\n{\n if( is_singular(\"your_post_type\"))\n {\n return \"\"; // Return empty\n }\n // Return my custom title\n return sprintf(\"%s %s\", $title, get_bloginfo('name'));\n}\n</code></pre>\n" }, { "answer_id": 369136, "author": "SnnSnn", "author_id": 165241, "author_profile": "https://wordpress.stackexchange.com/users/165241", "pm_score": 2, "selected": false, "text": "<p>I posted this answer for another question but since it is relevant and more up-to-date, I though it might be useful for some people.</p>\n<p>How document title is generated has changed since Wordpress v4.4.0. Now <code>wp_get_document_title</code> dictates how title is generated:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Displays title tag with content.\n *\n * @ignore\n * @since 4.1.0\n * @since 4.4.0 Improved title output replaced `wp_title()`.\n * @access private\n */\nfunction _wp_render_title_tag() {\n if ( ! current_theme_supports( 'title-tag' ) ) {\n return;\n }\n\n echo '&lt;title&gt;' . wp_get_document_title() . '&lt;/title&gt;' . &quot;\\n&quot;;\n}\n</code></pre>\n<p>Here is the code from v5.4.2. Here are the filters you can use to manipulate title tag:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wp_get_document_title() {\n /**\n * Filters the document title before it is generated.\n *\n * Passing a non-empty value will short-circuit wp_get_document_title(),\n * returning that value instead.\n *\n * @since 4.4.0\n *\n * @param string $title The document title. Default empty string.\n */\n $title = apply_filters( 'pre_get_document_title', '' );\n if ( ! empty( $title ) ) {\n return $title;\n }\n // --- snipped ---\n /**\n * Filters the separator for the document title.\n *\n * @since 4.4.0\n *\n * @param string $sep Document title separator. Default '-'.\n */\n $sep = apply_filters( 'document_title_separator', '-' );\n\n /**\n * Filters the parts of the document title.\n *\n * @since 4.4.0\n *\n * @param array $title {\n * The document title parts.\n *\n * @type string $title Title of the viewed page.\n * @type string $page Optional. Page number if paginated.\n * @type string $tagline Optional. Site description when on home page.\n * @type string $site Optional. Site title when not on home page.\n * }\n */\n $title = apply_filters( 'document_title_parts', $title );\n // --- snipped ---\n return $title;\n}\n</code></pre>\n<p>So here are two ways you can do it.</p>\n<p>First one uses <code>pre_get_document_title</code> filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_document_title( $title ) {\n return 'Here is the new title';\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 10 );\n</code></pre>\n<p>Second way uses <code>document_title_separator</code> and <code>document_title_parts</code> hooks for the title and the title seperator that are executed later in the function, after title is generated using functions like <code>single_term_title</code> or <code>post_type_archive_title</code> depending on the page and about to be outputted:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Custom function should return a string\nfunction custom_seperator( $sep ) {\n return '&gt;';\n}\nadd_filter( 'document_title_separator', 'custom_seperator', 10 );\n\n// Custom function should return an array\nfunction custom_html_title( $title ) {\n return array(\n 'title' =&gt; 'Custom Title',\n 'site' =&gt; 'Custom Site'\n );\n}\nadd_filter( 'document_title_parts', 'custom_html_title', 10 );\n</code></pre>\n" }, { "answer_id": 388573, "author": "Rami Alloush", "author_id": 146507, "author_profile": "https://wordpress.stackexchange.com/users/146507", "pm_score": 1, "selected": false, "text": "<p>Combining different answers, this is what worked for me on WordPress <code>v5.7.2</code> and my custom post type <code>company</code>. I was able to easily override the title on custom post page to add my Site Name at the end</p>\n<pre><code>function custom_document_title( $title ) {\n if( is_singular(&quot;company&quot;))\n {\n return sprintf(&quot;%s - %s&quot;, $title, get_bloginfo('name'));\n }\n return $title; // Return default title elsewhere\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 99 );\n</code></pre>\n" }, { "answer_id": 413954, "author": "Slingshot Design", "author_id": 229390, "author_profile": "https://wordpress.stackexchange.com/users/229390", "pm_score": 0, "selected": false, "text": "<p>The previous version didn't work for me in Wordpress 6.1.1 as it returned an empty $title. This version returns the page title + blog name or any custom text you want.</p>\n<pre><code>function custom_document_title( $title ) {\n global $post;\n $title = get_the_title($post);\n if( is_singular(&quot;event&quot;)){\n return sprintf(&quot;%s - %s&quot;, $title, 'Event Registration');\n } else {\n // Return the usual Wordpress style title\n return sprintf(&quot;%s - %s&quot;, $title, get_bloginfo('name'));\n }\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 99 );\n</code></pre>\n" } ]
2015/02/26
[ "https://wordpress.stackexchange.com/questions/179548", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68271/" ]
I am trying to list my news items in 3 columns in a vertical design: image, date, title. I'm having some trouble calling the featured image. Is there a specific function that would help me with this? Also add CSS style to list them in 3 columns? Website Example: <http://www.enterpriseflorida.com/why-florida/infrastructure/> My Code: ``` <?php $posts = get_posts( 'numberposts=2&order=DESC&orderby=post_title&category_name=news' ); foreach ( $posts as $post ) : start_wp(); ?> <?php toolbox_posted_on(); ?> <h4><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title() ; ?></a></h4> <?php endforeach; ?> </div> <a href="#" class="btn blue">Read All News</a> ```
First, let's change your `<title>` to ``` <title><?php wp_title(' | ', true, 'right'); ?></title> ``` Because adding to the title string in that was isn't very future-forward, instead it's best to use a filter to do any modifications to the title. So let's instead ad (in functions.php): ``` add_filter('wp_title', 'my_custom_title'); function my_custom_title( $title ) { // Return my custom title return sprintf("%s %s", $title, get_bloginfo('name')); } ``` Then let's extend this handy little title filter to do what you're wanting to do: ``` add_filter('wp_title', 'my_custom_title'); function my_custom_title( $title ) { if( is_singular("your_post_type")) { return ""; // Return empty } // Return my custom title return sprintf("%s %s", $title, get_bloginfo('name')); } ```
179,559
<p>I have a local Xampp wordpress installation that I am using as sort of an intranet with some people I work with. I require them to be able to access it on our LAN router -- I found that I needed to change the site url and links from <a href="http://localhost:8080" rel="noreferrer">http://localhost:8080</a> to my IP <a href="http://192.168.x.xx:8080" rel="noreferrer">http://192.168.x.xx:8080</a> for images and css to show.</p> <p>However, I have found that when we are connected to a different router, or my travel router, this IP changes and obviously makes it not work on the LAN. I'm not really wanting to search/replace and change the site name every time a new computer and/or server is hosting the local site.</p> <p>Question: So I'm really interested to see if there is a way to make the site/home URL dynamic to the hosting computer's current IP or computername. Or if I'm looking for the wrong type of solution.</p> <p>I have searched extensively for a solution to this, but I feel my problem is I'm not sure what terms to search for -- or if there is a better solution. I hope someone smart could point me in the right direction. </p> <p>-Based on my internet searches, I have tried a couple plugins - Relative URLs and "Root relative URLS" in hopes it would fix but it has not made a difference. -I have also set a static IP address in my travel router - however, the problem persists that I would need to change the ip address in the site if the computer changes. -I've also tried this in my wp-config:</p> <pre><code>&lt;?php define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST']); //add the next line if you have a subdirectory install define('WP_SITEURL', WP_HOME . '/wordpress'); </code></pre>
[ { "answer_id": 179790, "author": "Taberkinslaw", "author_id": 22990, "author_profile": "https://wordpress.stackexchange.com/users/22990", "pm_score": 4, "selected": true, "text": "<p>If anyone out there has a similar situation as me, I found a solution by adding:</p>\n\n<pre><code>/* That's all, stop editing! Happy blogging. */\n/** Absolute path to the WordPress directory. */\nif ( !defined('ABSPATH') )\ndefine('ABSPATH', dirname(__FILE__) . '/');\n/* THIS IS CUSTOM CODE CREATED AT ZEROFRACTAL TO MAKE SITE ACCESS DYNAMIC */\n$currenthost = \"http://\".$_SERVER['HTTP_HOST'];\n$currentpath = preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME']));\n$currentpath = preg_replace('/\\/wp.+/','',$currentpath);\ndefine('WP_HOME',$currenthost.$currentpath);\ndefine('WP_SITEURL',$currenthost.$currentpath);\ndefine('WP_CONTENT_URL', $currenthost.$currentpath.'/wp-content');\ndefine('WP_PLUGIN_URL', $currenthost.$currentpath.'/wp-content/plugins');\ndefine('DOMAIN_CURRENT_SITE', $currenthost.$currentpath );\n@define('ADMIN_COOKIE_PATH', './');\n</code></pre>\n\n<p>In the wp-config.php\nI found this solution on the site: <a href=\"http://davidmregister.com/dynamic-wp-siteurl/\" rel=\"noreferrer\">http://davidmregister.com/dynamic-wp-siteurl/</a></p>\n\n<p>Thanks everyone!</p>\n" }, { "answer_id": 218262, "author": "Jaded", "author_id": 89081, "author_profile": "https://wordpress.stackexchange.com/users/89081", "pm_score": 4, "selected": false, "text": "<p>I usually just avoid the issue entirely every time I create a new wordpress site:</p>\n\n<pre><code>define('WP_HOME', '/');\ndefine('WP_SITEURL', '/');\n</code></pre>\n\n<p>will cause wordpress to use root-relative urls for everything. Makes site migrations to other domains far easier. Ofc, if you access your site using a folder (eg. \"<a href=\"http://&lt;domain&gt;/blog\" rel=\"noreferrer\">http://&lt;domain&gt;/blog</a>\") you could change them to:</p>\n\n<pre><code>define('WP_HOME', '/blog/');\ndefine('WP_SITEURL', '/blog/');\n</code></pre>\n\n<p>For existing sites, make sure the database and any theme/plugin files are free from absolute urls generate by wordpress using the old WP_HOME and WP_SITEURL values.</p>\n\n<p>EDIT: just to clarify, you add these defines to your wp-config.php.</p>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22990/" ]
I have a local Xampp wordpress installation that I am using as sort of an intranet with some people I work with. I require them to be able to access it on our LAN router -- I found that I needed to change the site url and links from <http://localhost:8080> to my IP <http://192.168.x.xx:8080> for images and css to show. However, I have found that when we are connected to a different router, or my travel router, this IP changes and obviously makes it not work on the LAN. I'm not really wanting to search/replace and change the site name every time a new computer and/or server is hosting the local site. Question: So I'm really interested to see if there is a way to make the site/home URL dynamic to the hosting computer's current IP or computername. Or if I'm looking for the wrong type of solution. I have searched extensively for a solution to this, but I feel my problem is I'm not sure what terms to search for -- or if there is a better solution. I hope someone smart could point me in the right direction. -Based on my internet searches, I have tried a couple plugins - Relative URLs and "Root relative URLS" in hopes it would fix but it has not made a difference. -I have also set a static IP address in my travel router - however, the problem persists that I would need to change the ip address in the site if the computer changes. -I've also tried this in my wp-config: ``` <?php define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST']); //add the next line if you have a subdirectory install define('WP_SITEURL', WP_HOME . '/wordpress'); ```
If anyone out there has a similar situation as me, I found a solution by adding: ``` /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /* THIS IS CUSTOM CODE CREATED AT ZEROFRACTAL TO MAKE SITE ACCESS DYNAMIC */ $currenthost = "http://".$_SERVER['HTTP_HOST']; $currentpath = preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME'])); $currentpath = preg_replace('/\/wp.+/','',$currentpath); define('WP_HOME',$currenthost.$currentpath); define('WP_SITEURL',$currenthost.$currentpath); define('WP_CONTENT_URL', $currenthost.$currentpath.'/wp-content'); define('WP_PLUGIN_URL', $currenthost.$currentpath.'/wp-content/plugins'); define('DOMAIN_CURRENT_SITE', $currenthost.$currentpath ); @define('ADMIN_COOKIE_PATH', './'); ``` In the wp-config.php I found this solution on the site: <http://davidmregister.com/dynamic-wp-siteurl/> Thanks everyone!
179,585
<p>I have the following code in my theme's archive.php:</p> <pre><code>&lt;?php the_archive_title( '&lt;h1 class="page-title"&gt;', '&lt;/h1&gt;' ); ?&gt; </code></pre> <p>This gives me titles like "Category: Russia", "Tag: America", "Author: John".</p> <p>I would like to remove the "Category:", "Tag:" and "Author:" part and just display the category, tag and author names.</p> <p>Does anyone know how to accomplish this?</p> <p>Thank you.</p>
[ { "answer_id": 179590, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 8, "selected": true, "text": "<p>You can extend the <a href=\"https://developer.wordpress.org/reference/functions/get_the_archive_title/\" rel=\"noreferrer\"><code>get_the_archive_title</code> filter</a> which I've mentioned in <a href=\"https://wordpress.stackexchange.com/a/175903/31545\">this answer</a></p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('get_the_archive_title', function ($title) {\n if (is_category()) {\n $title = single_cat_title('', false);\n } elseif (is_tag()) {\n $title = single_tag_title('', false);\n } elseif (is_author()) {\n $title = '&lt;span class=&quot;vcard&quot;&gt;' . get_the_author() . '&lt;/span&gt;';\n } elseif (is_tax()) { //for custom post types\n $title = sprintf(__('%1$s'), single_term_title('', false));\n } elseif (is_post_type_archive()) {\n $title = post_type_archive_title('', false);\n }\n return $title;\n});\n</code></pre>\n" }, { "answer_id": 219767, "author": "Тимофей А.", "author_id": 90010, "author_profile": "https://wordpress.stackexchange.com/users/90010", "pm_score": 6, "selected": false, "text": "<p>Use function <code>single_term_title()</code></p>\n" }, { "answer_id": 235838, "author": "Hoang Oanh", "author_id": 100956, "author_profile": "https://wordpress.stackexchange.com/users/100956", "pm_score": 2, "selected": false, "text": "<p><code>echo '&lt;h1 class=\"page-title\"&gt;' . single_cat_title( '', false ) . '&lt;/h1&gt;';</code> \nin taxonomy-category.php outside public of theme.</p>\n" }, { "answer_id": 238372, "author": "Dragan Nikolic", "author_id": 102292, "author_profile": "https://wordpress.stackexchange.com/users/102292", "pm_score": -1, "selected": false, "text": "<p>directory: <code>wp-includes</code></p>\n\n<p>file: <code>general-template.php</code></p>\n\n<p>find function: <code>get_the_archive_title()</code>\nchange:</p>\n\n<pre><code>if ( is_category() ) {\n $title = sprintf( __( 'Category: %s' ), single_cat_title( '', false ) );\n } elseif ( is_tag() ) {\n $title = sprintf( __( 'Tag: %s' ), single_tag_title( '', false ) );\n } elseif ( is_author() ) {\n $title = sprintf( __( 'Autor: %s' ), '&lt;span class=\"vcard\"&gt;' . get_the_author() . '&lt;/span&gt;' );\n }\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if ( is_category() ) {\n $title = sprintf( __( '%s' ), single_cat_title( '', false ) );\n } elseif ( is_tag() ) {\n $title = sprintf( __( '%s' ), single_tag_title( '', false ) );\n } elseif ( is_author() ) {\n $title = sprintf( __( '%s' ), '&lt;span class=\"vcard\"&gt;' . get_the_author() . '&lt;/span&gt;' );\n }//if you want to remove or just change text if you need to\n</code></pre>\n" }, { "answer_id": 247845, "author": "Tisch", "author_id": 33644, "author_profile": "https://wordpress.stackexchange.com/users/33644", "pm_score": 4, "selected": false, "text": "<p>I feel like this is over simplifying things, but this is what I did... </p>\n\n<pre><code>&lt;h1&gt;&lt;?php echo str_replace(\"Archives: \", \"\", get_the_archive_title()); ?&gt;&lt;/h1&gt;\n</code></pre>\n" }, { "answer_id": 276448, "author": "Mike Castro Demaria", "author_id": 49308, "author_profile": "https://wordpress.stackexchange.com/users/49308", "pm_score": 5, "selected": false, "text": "<p>For CPT title Without word: ‘Archive’:</p>\n\n<p>If you are building custom archive template for a CPT, and want to output just the title of the CPT with no extra word like “Archive” use following function instead:</p>\n\n<pre><code>post_type_archive_title();\n</code></pre>\n\n<p>From <a href=\"https://developer.wordpress.org/reference/functions/post_type_archive_title/\" rel=\"noreferrer\">developer.wordpress.org</a></p>\n" }, { "answer_id": 295361, "author": "Xiomara", "author_id": 137663, "author_profile": "https://wordpress.stackexchange.com/users/137663", "pm_score": 1, "selected": false, "text": "<p>You can use the following to just have only the title without the prefix</p>\n\n<pre><code>single_cat_title();\n</code></pre>\n" }, { "answer_id": 303520, "author": "Yaworek", "author_id": 143581, "author_profile": "https://wordpress.stackexchange.com/users/143581", "pm_score": 2, "selected": false, "text": "<p>I would use a filter and put it in a file functions.php </p>\n\n<pre><code>add_filter( 'get_the_archive_title', 'replaceCategoryName'); \n function replaceCategoryName ($title) {\n\n $title = single_cat_title( '', false );\n return $title; \n}\n</code></pre>\n" }, { "answer_id": 349886, "author": "t-jam", "author_id": 21222, "author_profile": "https://wordpress.stackexchange.com/users/21222", "pm_score": 0, "selected": false, "text": "<p>Assuming the format is always: <code>Prefix: Archive Name</code>, we can just find the first colon followed by a space, and only show the content after this, using <a href=\"https://developer.wordpress.org/reference/functions/get_the_archive_title/\" rel=\"nofollow noreferrer\">get_the_archive_title()</a> with PHP's <a href=\"https://www.php.net/manual/en/function.substr.php\" rel=\"nofollow noreferrer\">substr()</a> and <a href=\"https://www.php.net/manual/en/function.strpos.php\" rel=\"nofollow noreferrer\">strpos()</a> functions.</p>\n\n<pre><code>&lt;?php // Only show the portion of the string following the first \": \"\n echo substr(get_the_archive_title(), strpos(get_the_archive_title(), ': ') + 2);\n?&gt;\n</code></pre>\n" }, { "answer_id": 386036, "author": "Andrew J Klimek", "author_id": 75024, "author_profile": "https://wordpress.stackexchange.com/users/75024", "pm_score": 3, "selected": false, "text": "<p>as of Wordpress 5.5 you can remove the prefix with <a href=\"https://developer.wordpress.org/reference/hooks/get_the_archive_title_prefix/\" rel=\"noreferrer\">this hook</a>:</p>\n<p><code>add_filter('get_the_archive_title_prefix','__return_false');</code></p>\n" }, { "answer_id": 402681, "author": "Mamunur Rashid", "author_id": 148416, "author_profile": "https://wordpress.stackexchange.com/users/148416", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter('post_type_archive_title', '__return_empty_string', 5);\n</code></pre>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68284/" ]
I have the following code in my theme's archive.php: ``` <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); ?> ``` This gives me titles like "Category: Russia", "Tag: America", "Author: John". I would like to remove the "Category:", "Tag:" and "Author:" part and just display the category, tag and author names. Does anyone know how to accomplish this? Thank you.
You can extend the [`get_the_archive_title` filter](https://developer.wordpress.org/reference/functions/get_the_archive_title/) which I've mentioned in [this answer](https://wordpress.stackexchange.com/a/175903/31545) ```php add_filter('get_the_archive_title', function ($title) { if (is_category()) { $title = single_cat_title('', false); } elseif (is_tag()) { $title = single_tag_title('', false); } elseif (is_author()) { $title = '<span class="vcard">' . get_the_author() . '</span>'; } elseif (is_tax()) { //for custom post types $title = sprintf(__('%1$s'), single_term_title('', false)); } elseif (is_post_type_archive()) { $title = post_type_archive_title('', false); } return $title; }); ```
179,614
<p>I want to add a text in admin login page, i searched a lot about this but can't find any thing else a plugin (its my last option).</p> <p>I also use this filter:</p> <pre><code>function my_login_logo_url_title() { return 'Your Site Name and Info'; } add_filter( 'login_headertitle', 'my_login_logo_url_title' ); </code></pre> <p>But nothing happen is there any other hook or filter please tell me its urgent.</p>
[ { "answer_id": 179590, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 8, "selected": true, "text": "<p>You can extend the <a href=\"https://developer.wordpress.org/reference/functions/get_the_archive_title/\" rel=\"noreferrer\"><code>get_the_archive_title</code> filter</a> which I've mentioned in <a href=\"https://wordpress.stackexchange.com/a/175903/31545\">this answer</a></p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('get_the_archive_title', function ($title) {\n if (is_category()) {\n $title = single_cat_title('', false);\n } elseif (is_tag()) {\n $title = single_tag_title('', false);\n } elseif (is_author()) {\n $title = '&lt;span class=&quot;vcard&quot;&gt;' . get_the_author() . '&lt;/span&gt;';\n } elseif (is_tax()) { //for custom post types\n $title = sprintf(__('%1$s'), single_term_title('', false));\n } elseif (is_post_type_archive()) {\n $title = post_type_archive_title('', false);\n }\n return $title;\n});\n</code></pre>\n" }, { "answer_id": 219767, "author": "Тимофей А.", "author_id": 90010, "author_profile": "https://wordpress.stackexchange.com/users/90010", "pm_score": 6, "selected": false, "text": "<p>Use function <code>single_term_title()</code></p>\n" }, { "answer_id": 235838, "author": "Hoang Oanh", "author_id": 100956, "author_profile": "https://wordpress.stackexchange.com/users/100956", "pm_score": 2, "selected": false, "text": "<p><code>echo '&lt;h1 class=\"page-title\"&gt;' . single_cat_title( '', false ) . '&lt;/h1&gt;';</code> \nin taxonomy-category.php outside public of theme.</p>\n" }, { "answer_id": 238372, "author": "Dragan Nikolic", "author_id": 102292, "author_profile": "https://wordpress.stackexchange.com/users/102292", "pm_score": -1, "selected": false, "text": "<p>directory: <code>wp-includes</code></p>\n\n<p>file: <code>general-template.php</code></p>\n\n<p>find function: <code>get_the_archive_title()</code>\nchange:</p>\n\n<pre><code>if ( is_category() ) {\n $title = sprintf( __( 'Category: %s' ), single_cat_title( '', false ) );\n } elseif ( is_tag() ) {\n $title = sprintf( __( 'Tag: %s' ), single_tag_title( '', false ) );\n } elseif ( is_author() ) {\n $title = sprintf( __( 'Autor: %s' ), '&lt;span class=\"vcard\"&gt;' . get_the_author() . '&lt;/span&gt;' );\n }\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if ( is_category() ) {\n $title = sprintf( __( '%s' ), single_cat_title( '', false ) );\n } elseif ( is_tag() ) {\n $title = sprintf( __( '%s' ), single_tag_title( '', false ) );\n } elseif ( is_author() ) {\n $title = sprintf( __( '%s' ), '&lt;span class=\"vcard\"&gt;' . get_the_author() . '&lt;/span&gt;' );\n }//if you want to remove or just change text if you need to\n</code></pre>\n" }, { "answer_id": 247845, "author": "Tisch", "author_id": 33644, "author_profile": "https://wordpress.stackexchange.com/users/33644", "pm_score": 4, "selected": false, "text": "<p>I feel like this is over simplifying things, but this is what I did... </p>\n\n<pre><code>&lt;h1&gt;&lt;?php echo str_replace(\"Archives: \", \"\", get_the_archive_title()); ?&gt;&lt;/h1&gt;\n</code></pre>\n" }, { "answer_id": 276448, "author": "Mike Castro Demaria", "author_id": 49308, "author_profile": "https://wordpress.stackexchange.com/users/49308", "pm_score": 5, "selected": false, "text": "<p>For CPT title Without word: ‘Archive’:</p>\n\n<p>If you are building custom archive template for a CPT, and want to output just the title of the CPT with no extra word like “Archive” use following function instead:</p>\n\n<pre><code>post_type_archive_title();\n</code></pre>\n\n<p>From <a href=\"https://developer.wordpress.org/reference/functions/post_type_archive_title/\" rel=\"noreferrer\">developer.wordpress.org</a></p>\n" }, { "answer_id": 295361, "author": "Xiomara", "author_id": 137663, "author_profile": "https://wordpress.stackexchange.com/users/137663", "pm_score": 1, "selected": false, "text": "<p>You can use the following to just have only the title without the prefix</p>\n\n<pre><code>single_cat_title();\n</code></pre>\n" }, { "answer_id": 303520, "author": "Yaworek", "author_id": 143581, "author_profile": "https://wordpress.stackexchange.com/users/143581", "pm_score": 2, "selected": false, "text": "<p>I would use a filter and put it in a file functions.php </p>\n\n<pre><code>add_filter( 'get_the_archive_title', 'replaceCategoryName'); \n function replaceCategoryName ($title) {\n\n $title = single_cat_title( '', false );\n return $title; \n}\n</code></pre>\n" }, { "answer_id": 349886, "author": "t-jam", "author_id": 21222, "author_profile": "https://wordpress.stackexchange.com/users/21222", "pm_score": 0, "selected": false, "text": "<p>Assuming the format is always: <code>Prefix: Archive Name</code>, we can just find the first colon followed by a space, and only show the content after this, using <a href=\"https://developer.wordpress.org/reference/functions/get_the_archive_title/\" rel=\"nofollow noreferrer\">get_the_archive_title()</a> with PHP's <a href=\"https://www.php.net/manual/en/function.substr.php\" rel=\"nofollow noreferrer\">substr()</a> and <a href=\"https://www.php.net/manual/en/function.strpos.php\" rel=\"nofollow noreferrer\">strpos()</a> functions.</p>\n\n<pre><code>&lt;?php // Only show the portion of the string following the first \": \"\n echo substr(get_the_archive_title(), strpos(get_the_archive_title(), ': ') + 2);\n?&gt;\n</code></pre>\n" }, { "answer_id": 386036, "author": "Andrew J Klimek", "author_id": 75024, "author_profile": "https://wordpress.stackexchange.com/users/75024", "pm_score": 3, "selected": false, "text": "<p>as of Wordpress 5.5 you can remove the prefix with <a href=\"https://developer.wordpress.org/reference/hooks/get_the_archive_title_prefix/\" rel=\"noreferrer\">this hook</a>:</p>\n<p><code>add_filter('get_the_archive_title_prefix','__return_false');</code></p>\n" }, { "answer_id": 402681, "author": "Mamunur Rashid", "author_id": 148416, "author_profile": "https://wordpress.stackexchange.com/users/148416", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter('post_type_archive_title', '__return_empty_string', 5);\n</code></pre>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179614", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64316/" ]
I want to add a text in admin login page, i searched a lot about this but can't find any thing else a plugin (its my last option). I also use this filter: ``` function my_login_logo_url_title() { return 'Your Site Name and Info'; } add_filter( 'login_headertitle', 'my_login_logo_url_title' ); ``` But nothing happen is there any other hook or filter please tell me its urgent.
You can extend the [`get_the_archive_title` filter](https://developer.wordpress.org/reference/functions/get_the_archive_title/) which I've mentioned in [this answer](https://wordpress.stackexchange.com/a/175903/31545) ```php add_filter('get_the_archive_title', function ($title) { if (is_category()) { $title = single_cat_title('', false); } elseif (is_tag()) { $title = single_tag_title('', false); } elseif (is_author()) { $title = '<span class="vcard">' . get_the_author() . '</span>'; } elseif (is_tax()) { //for custom post types $title = sprintf(__('%1$s'), single_term_title('', false)); } elseif (is_post_type_archive()) { $title = post_type_archive_title('', false); } return $title; }); ```
179,618
<p>I would like to implement an <strong>inline file uploader</strong> to my plugin's option page as introduced in new media grid view of the WP media library:</p> <p><img src="https://i.stack.imgur.com/F2xeo.png" alt="enter image description here"></p> <p>I imagine having this drag &amp; drop uploader in the page and getting an JSON object of either errors or attachment data back in JS when used.</p> <p>As far as I know there is a <code>wp.media.view.UploaderInline</code> class present in <code>wp-includes/js/media-views.js</code> but I have no idea of how to implement that in combination with the given markup.</p> <p>The only resources I found are on how to use the media modal (introduced in v3.5) to upload and add files to a page. But having the uploader inline would be much better for my case since I don't want the media library to show up in the process.</p> <p>Has anyone experience implementing this to get me on track?</p> <p>Thx</p>
[ { "answer_id": 181524, "author": "DiverseAndRemote.com", "author_id": 23690, "author_profile": "https://wordpress.stackexchange.com/users/23690", "pm_score": 1, "selected": false, "text": "<p>The first thing you'll need to do is call <code>wp_enqueue_media</code>. A safe place for this might be in the <code>admin_init</code> action with some conditional around it.</p>\n\n<pre><code>add_action( 'admin_init', function() {\n $screen = get_current_screen();\n\n if ( ! $screen || 'my-admin-page-slug' !== $screen-&gt;id ) {\n return;\n }\n\n wp_enqueue_media();\n} );\n</code></pre>\n\n<p>Then in your admin page code you'd add some inline javascript (or enqueue it if you want to do it cleanly)</p>\n\n<pre><code>function my_admin_page_callback() {\n\n ...\n?&gt;\n &lt;a href=\"#\" class=\"primary button upload\"&gt;Upload&lt;/a&gt;\n &lt;script type=\"text/javascript\"&gt;\n $('.upload.button').click(function(e) {\n e.preventDefault();\n\n var custom_uploader = wp.media({\n title: 'Custom Title',\n button: {\n text: 'Custom Button Text'\n },\n multiple: false // Set this to true to allow multiple files to be selected\n })\n .on('select', function() {\n var attachment = custom_uploader.state().get('selection').first().toJSON();\n // Do something with attachment.url;\n // Do something with attachment.id;\n })\n .open();\n });\n &lt;/script&gt;\n&lt;?php\n ...\n}\n</code></pre>\n\n<p>Getting the drag and drop box might prove a little difficult but if you do a little digging of your own you might be able to find it.</p>\n" }, { "answer_id": 182038, "author": "hm711", "author_id": 51687, "author_profile": "https://wordpress.stackexchange.com/users/51687", "pm_score": 3, "selected": true, "text": "<p>Okay, here is what I came up with: It's all about using the <a href=\"http://plupload.com/\" rel=\"nofollow\">plupload library</a> that comes shipped with WP.</p>\n\n<h2>1. Add a <code>&lt;div&gt;</code> to your plugin's option page that later becomes the drag'n'drop area</h2>\n\n<pre><code> &lt;div class=\"your-plugin-uploader multiple\"&gt;\n &lt;input id=\"your-plugin-uploader-button\" type=\"button\" value=\"&lt;?php esc_attr_e( 'Select Files' ); ?&gt;\" class=\"your-plugin-uploader-button button\"&gt;\n &lt;span class=\"ajaxnonce\" id=\"&lt;?php echo wp_create_nonce( __FILE__ ); ?&gt;\"&gt;&lt;/span&gt;\n &lt;/div&gt;\n</code></pre>\n\n<h2>2. Register your plugin JS and make sure you define <code>plupload-all</code> as a dependency for your script</h2>\n\n<pre><code> function se179618_admin_js() {\n wp_register_script( 'your-plugin', WP_PLUGIN_URL . '/your-plugin/js/your-plugin.js', array( 'jquery', 'plupload-all' ) );\n }\n add_action( 'admin_enqueue_scripts', 'se179618_admin_js' );\n</code></pre>\n\n<h2>3. Write some plupload settings to the page's <code>&lt;head&gt;</code></h2>\n\n<pre><code> function se179618_admin_head() {\n $uploader_options = array(\n 'runtimes' =&gt; 'html5,silverlight,flash,html4',\n 'browse_button' =&gt; 'my-plugin-uploader-button', \n 'container' =&gt; 'my-plugin-uploader', \n 'drop_element' =&gt; 'my-plugin-uploader', \n 'file_data_name' =&gt; 'async-upload', \n 'multiple_queues' =&gt; true,\n 'max_file_size' =&gt; wp_max_upload_size() . 'b',\n 'url' =&gt; admin_url( 'admin-ajax.php' ),\n 'flash_swf_url' =&gt; includes_url( 'js/plupload/plupload.flash.swf' ),\n 'silverlight_xap_url' =&gt; includes_url( 'js/plupload/plupload.silverlight.xap' ),\n 'filters' =&gt; array( \n array( \n 'title' =&gt; __( 'Allowed Files' ), \n 'extensions' =&gt; '*'\n ) \n ),\n 'multipart' =&gt; true,\n 'urlstream_upload' =&gt; true,\n 'multi_selection' =&gt; true, \n 'multipart_params' =&gt; array(\n '_ajax_nonce' =&gt; '', \n 'action' =&gt; 'my-plugin-upload-action' \n )\n );\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var global_uploader_options=&lt;?php echo json_encode( $uploader_options ); ?&gt;;\n &lt;/script&gt;\n &lt;?php\n }\n add_action( 'admin_head', 'se179618_admin_head' );\n</code></pre>\n\n<h2>4. Add the action called by the AJAX uploader</h2>\n\n<pre><code> function se179618_ajax_action() {\n // check ajax nonce\n check_ajax_referer( __FILE__ );\n\n if( current_user_can( 'upload_files' ) ) {\n $response = array();\n\n // handle file upload\n $id = media_handle_upload( \n 'async-upload',\n 0, \n array( \n 'test_form' =&gt; true, \n 'action' =&gt; 'my-plugin-upload-action' \n )\n );\n\n // send the file' url as response\n if( is_wp_error( $id ) ) {\n $response['status'] = 'error';\n $response['error'] = $id-&gt;get_error_messages();\n } else {\n $response['status'] = 'success';\n\n $src = wp_get_attachment_image_src( $id, 'thumbnail' );\n $response['attachment'] = array();\n $response['attachment']['id'] = $id;\n $response['attachment']['src'] = $src[0];\n }\n\n }\n\n echo json_encode( $response );\n exit;\n }\n\n add_action( 'wp_ajax_my-plugin-upload-action', 'se179618_ajax_action' ); \n</code></pre>\n\n<h2>5. Initiate the uploader in your plugin's JS</h2>\n\n<pre><code> jQuery( document ).ready( function() {\n\n if( jQuery( '.your-plugin-uploader' ).length &gt; 0 ) {\n var options = false;\n var container = jQuery( '.your-plugin-uploader' );\n options = JSON.parse( JSON.stringify( global_uploader_options ) );\n options['multipart_params']['_ajax_nonce'] = container.find( '.ajaxnonce' ).attr( 'id' );\n\n if( container.hasClass( 'multiple' ) ) {\n options['multi_selection'] = true;\n }\n\n var uploader = new plupload.Uploader( options );\n uploader.init();\n\n // EVENTS\n // init\n uploader.bind( 'Init', function( up ) {\n console.log( 'Init', up );\n } );\n\n // file added\n uploader.bind( 'FilesAdded', function( up, files ) {\n jQuery.each( files, function( i, file ) {\n console.log( 'File Added', i, file );\n } );\n\n up.refresh();\n up.start();\n } );\n\n // upload progress\n uploader.bind( 'UploadProgress', function( up, file ) {\n console.log( 'Progress', up, file )\n } );\n\n // file uploaded\n uploader.bind( 'FileUploaded', function( up, file, response ) {\n response = jQuery.parseJSON( response.response );\n\n if( response['status'] == 'success' ) {\n console.log( 'Success', up, file, response );\n } else {\n console.log( 'Error', up, file, response );\n }\n\n } );\n }\n\n } );\n</code></pre>\n" }, { "answer_id": 317745, "author": "Jonas Lundman", "author_id": 43172, "author_profile": "https://wordpress.stackexchange.com/users/43172", "pm_score": 2, "selected": false, "text": "<p>Here is an example for wp version 4.7 and above. The task is simple. This code is directly <strong>cloned</strong> script taken from the <strong>default Wordpress Add new page</strong> (media-new.php).</p>\n\n<pre><code>function my_admin_enqueue_scripts() {\n wp_enqueue_script('plupload-handlers');\n}\nadd_action('admin_enqueue_scripts', 'my_admin_enqueue_scripts');\n</code></pre>\n\n<p>Add this html on your options page. Make shure you keep this <strong>outside your own <code>&lt;form&gt;</code> element</strong>. To keep the variables out of global scope, I recommend to wrap the html output inside a function. This example is lending the top admin notices container to show the area on every admin page... so you can test it without option page.</p>\n\n<pre><code>function my_upload_new_media_html(){\n\n /* everything is copied from media-new.php */\n /* translated, and old browser option is there as well */\n\n $title = __('Upload New Media');\n\n $post_id = 0;\n if(isset($_REQUEST['post_id'])){\n $post_id = absint($_REQUEST['post_id']);\n if(!get_post($post_id) || !current_user_can('edit_post', $post_id)) $post_id = 0;\n }\n\n if($_POST){\n if(isset($_POST['html-upload']) &amp;&amp; !empty($_FILES)){\n check_admin_referer('media-form');\n // Upload File button was clicked\n $upload_id = media_handle_upload('async-upload', $post_id);\n if(is_wp_error($upload_id)){\n wp_die($upload_id);\n }\n }\n wp_redirect(admin_url('upload.php'));\n exit;\n }\n\n $form_class = 'media-upload-form type-form validate';\n if(get_user_setting('uploader') || isset( $_GET['browser-uploader']))\n $form_class .= ' html-uploader';\n\n?&gt;\n\n&lt;div class=\"wrap\"&gt;\n &lt;h1&gt;&lt;?php echo esc_html( $title ); ?&gt;&lt;/h1&gt;\n\n &lt;form enctype=\"multipart/form-data\" method=\"post\" action=\"&lt;?php echo admin_url('media-new.php'); ?&gt;\" class=\"&lt;?php echo esc_attr( $form_class ); ?&gt;\" id=\"file-form\"&gt;\n\n &lt;?php media_upload_form(); ?&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n var post_id = &lt;?php echo $post_id; ?&gt;, shortform = 3;\n &lt;/script&gt;\n &lt;input type=\"hidden\" name=\"post_id\" id=\"post_id\" value=\"&lt;?php echo $post_id; ?&gt;\" /&gt;\n &lt;?php wp_nonce_field('media-form'); ?&gt;\n &lt;div id=\"media-items\" class=\"hide-if-no-js\"&gt;&lt;/div&gt;\n &lt;/form&gt;\n&lt;/div&gt;\n\n&lt;?php\n}\nadd_action('all_admin_notices', 'my_upload_new_media_html');\n</code></pre>\n\n<p>And Boom, its there.</p>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179618", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51687/" ]
I would like to implement an **inline file uploader** to my plugin's option page as introduced in new media grid view of the WP media library: ![enter image description here](https://i.stack.imgur.com/F2xeo.png) I imagine having this drag & drop uploader in the page and getting an JSON object of either errors or attachment data back in JS when used. As far as I know there is a `wp.media.view.UploaderInline` class present in `wp-includes/js/media-views.js` but I have no idea of how to implement that in combination with the given markup. The only resources I found are on how to use the media modal (introduced in v3.5) to upload and add files to a page. But having the uploader inline would be much better for my case since I don't want the media library to show up in the process. Has anyone experience implementing this to get me on track? Thx
Okay, here is what I came up with: It's all about using the [plupload library](http://plupload.com/) that comes shipped with WP. 1. Add a `<div>` to your plugin's option page that later becomes the drag'n'drop area ------------------------------------------------------------------------------------- ``` <div class="your-plugin-uploader multiple"> <input id="your-plugin-uploader-button" type="button" value="<?php esc_attr_e( 'Select Files' ); ?>" class="your-plugin-uploader-button button"> <span class="ajaxnonce" id="<?php echo wp_create_nonce( __FILE__ ); ?>"></span> </div> ``` 2. Register your plugin JS and make sure you define `plupload-all` as a dependency for your script -------------------------------------------------------------------------------------------------- ``` function se179618_admin_js() { wp_register_script( 'your-plugin', WP_PLUGIN_URL . '/your-plugin/js/your-plugin.js', array( 'jquery', 'plupload-all' ) ); } add_action( 'admin_enqueue_scripts', 'se179618_admin_js' ); ``` 3. Write some plupload settings to the page's `<head>` ------------------------------------------------------ ``` function se179618_admin_head() { $uploader_options = array( 'runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => 'my-plugin-uploader-button', 'container' => 'my-plugin-uploader', 'drop_element' => 'my-plugin-uploader', 'file_data_name' => 'async-upload', 'multiple_queues' => true, 'max_file_size' => wp_max_upload_size() . 'b', 'url' => admin_url( 'admin-ajax.php' ), 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ), 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ), 'filters' => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*' ) ), 'multipart' => true, 'urlstream_upload' => true, 'multi_selection' => true, 'multipart_params' => array( '_ajax_nonce' => '', 'action' => 'my-plugin-upload-action' ) ); ?> <script type="text/javascript"> var global_uploader_options=<?php echo json_encode( $uploader_options ); ?>; </script> <?php } add_action( 'admin_head', 'se179618_admin_head' ); ``` 4. Add the action called by the AJAX uploader --------------------------------------------- ``` function se179618_ajax_action() { // check ajax nonce check_ajax_referer( __FILE__ ); if( current_user_can( 'upload_files' ) ) { $response = array(); // handle file upload $id = media_handle_upload( 'async-upload', 0, array( 'test_form' => true, 'action' => 'my-plugin-upload-action' ) ); // send the file' url as response if( is_wp_error( $id ) ) { $response['status'] = 'error'; $response['error'] = $id->get_error_messages(); } else { $response['status'] = 'success'; $src = wp_get_attachment_image_src( $id, 'thumbnail' ); $response['attachment'] = array(); $response['attachment']['id'] = $id; $response['attachment']['src'] = $src[0]; } } echo json_encode( $response ); exit; } add_action( 'wp_ajax_my-plugin-upload-action', 'se179618_ajax_action' ); ``` 5. Initiate the uploader in your plugin's JS -------------------------------------------- ``` jQuery( document ).ready( function() { if( jQuery( '.your-plugin-uploader' ).length > 0 ) { var options = false; var container = jQuery( '.your-plugin-uploader' ); options = JSON.parse( JSON.stringify( global_uploader_options ) ); options['multipart_params']['_ajax_nonce'] = container.find( '.ajaxnonce' ).attr( 'id' ); if( container.hasClass( 'multiple' ) ) { options['multi_selection'] = true; } var uploader = new plupload.Uploader( options ); uploader.init(); // EVENTS // init uploader.bind( 'Init', function( up ) { console.log( 'Init', up ); } ); // file added uploader.bind( 'FilesAdded', function( up, files ) { jQuery.each( files, function( i, file ) { console.log( 'File Added', i, file ); } ); up.refresh(); up.start(); } ); // upload progress uploader.bind( 'UploadProgress', function( up, file ) { console.log( 'Progress', up, file ) } ); // file uploaded uploader.bind( 'FileUploaded', function( up, file, response ) { response = jQuery.parseJSON( response.response ); if( response['status'] == 'success' ) { console.log( 'Success', up, file, response ); } else { console.log( 'Error', up, file, response ); } } ); } } ); ```
179,654
<p>When I use Joomla I can change a core string using the language files. So where it would say "Cart" you would go into the language file and change it to what you want it to say.</p> <p>I want to be able to do this for one of our client's websites which uses WordPress. Is this possible? I am using the wpex-adapt theme.</p> <p>The exact bit I want to change is on the Portfolio page on the individual item page where it says "newer" and "older" which I want to change to "previous" and "next".</p> <p>Any suggestions will be greatly appreciated.</p>
[ { "answer_id": 181524, "author": "DiverseAndRemote.com", "author_id": 23690, "author_profile": "https://wordpress.stackexchange.com/users/23690", "pm_score": 1, "selected": false, "text": "<p>The first thing you'll need to do is call <code>wp_enqueue_media</code>. A safe place for this might be in the <code>admin_init</code> action with some conditional around it.</p>\n\n<pre><code>add_action( 'admin_init', function() {\n $screen = get_current_screen();\n\n if ( ! $screen || 'my-admin-page-slug' !== $screen-&gt;id ) {\n return;\n }\n\n wp_enqueue_media();\n} );\n</code></pre>\n\n<p>Then in your admin page code you'd add some inline javascript (or enqueue it if you want to do it cleanly)</p>\n\n<pre><code>function my_admin_page_callback() {\n\n ...\n?&gt;\n &lt;a href=\"#\" class=\"primary button upload\"&gt;Upload&lt;/a&gt;\n &lt;script type=\"text/javascript\"&gt;\n $('.upload.button').click(function(e) {\n e.preventDefault();\n\n var custom_uploader = wp.media({\n title: 'Custom Title',\n button: {\n text: 'Custom Button Text'\n },\n multiple: false // Set this to true to allow multiple files to be selected\n })\n .on('select', function() {\n var attachment = custom_uploader.state().get('selection').first().toJSON();\n // Do something with attachment.url;\n // Do something with attachment.id;\n })\n .open();\n });\n &lt;/script&gt;\n&lt;?php\n ...\n}\n</code></pre>\n\n<p>Getting the drag and drop box might prove a little difficult but if you do a little digging of your own you might be able to find it.</p>\n" }, { "answer_id": 182038, "author": "hm711", "author_id": 51687, "author_profile": "https://wordpress.stackexchange.com/users/51687", "pm_score": 3, "selected": true, "text": "<p>Okay, here is what I came up with: It's all about using the <a href=\"http://plupload.com/\" rel=\"nofollow\">plupload library</a> that comes shipped with WP.</p>\n\n<h2>1. Add a <code>&lt;div&gt;</code> to your plugin's option page that later becomes the drag'n'drop area</h2>\n\n<pre><code> &lt;div class=\"your-plugin-uploader multiple\"&gt;\n &lt;input id=\"your-plugin-uploader-button\" type=\"button\" value=\"&lt;?php esc_attr_e( 'Select Files' ); ?&gt;\" class=\"your-plugin-uploader-button button\"&gt;\n &lt;span class=\"ajaxnonce\" id=\"&lt;?php echo wp_create_nonce( __FILE__ ); ?&gt;\"&gt;&lt;/span&gt;\n &lt;/div&gt;\n</code></pre>\n\n<h2>2. Register your plugin JS and make sure you define <code>plupload-all</code> as a dependency for your script</h2>\n\n<pre><code> function se179618_admin_js() {\n wp_register_script( 'your-plugin', WP_PLUGIN_URL . '/your-plugin/js/your-plugin.js', array( 'jquery', 'plupload-all' ) );\n }\n add_action( 'admin_enqueue_scripts', 'se179618_admin_js' );\n</code></pre>\n\n<h2>3. Write some plupload settings to the page's <code>&lt;head&gt;</code></h2>\n\n<pre><code> function se179618_admin_head() {\n $uploader_options = array(\n 'runtimes' =&gt; 'html5,silverlight,flash,html4',\n 'browse_button' =&gt; 'my-plugin-uploader-button', \n 'container' =&gt; 'my-plugin-uploader', \n 'drop_element' =&gt; 'my-plugin-uploader', \n 'file_data_name' =&gt; 'async-upload', \n 'multiple_queues' =&gt; true,\n 'max_file_size' =&gt; wp_max_upload_size() . 'b',\n 'url' =&gt; admin_url( 'admin-ajax.php' ),\n 'flash_swf_url' =&gt; includes_url( 'js/plupload/plupload.flash.swf' ),\n 'silverlight_xap_url' =&gt; includes_url( 'js/plupload/plupload.silverlight.xap' ),\n 'filters' =&gt; array( \n array( \n 'title' =&gt; __( 'Allowed Files' ), \n 'extensions' =&gt; '*'\n ) \n ),\n 'multipart' =&gt; true,\n 'urlstream_upload' =&gt; true,\n 'multi_selection' =&gt; true, \n 'multipart_params' =&gt; array(\n '_ajax_nonce' =&gt; '', \n 'action' =&gt; 'my-plugin-upload-action' \n )\n );\n ?&gt;\n &lt;script type=\"text/javascript\"&gt;\n var global_uploader_options=&lt;?php echo json_encode( $uploader_options ); ?&gt;;\n &lt;/script&gt;\n &lt;?php\n }\n add_action( 'admin_head', 'se179618_admin_head' );\n</code></pre>\n\n<h2>4. Add the action called by the AJAX uploader</h2>\n\n<pre><code> function se179618_ajax_action() {\n // check ajax nonce\n check_ajax_referer( __FILE__ );\n\n if( current_user_can( 'upload_files' ) ) {\n $response = array();\n\n // handle file upload\n $id = media_handle_upload( \n 'async-upload',\n 0, \n array( \n 'test_form' =&gt; true, \n 'action' =&gt; 'my-plugin-upload-action' \n )\n );\n\n // send the file' url as response\n if( is_wp_error( $id ) ) {\n $response['status'] = 'error';\n $response['error'] = $id-&gt;get_error_messages();\n } else {\n $response['status'] = 'success';\n\n $src = wp_get_attachment_image_src( $id, 'thumbnail' );\n $response['attachment'] = array();\n $response['attachment']['id'] = $id;\n $response['attachment']['src'] = $src[0];\n }\n\n }\n\n echo json_encode( $response );\n exit;\n }\n\n add_action( 'wp_ajax_my-plugin-upload-action', 'se179618_ajax_action' ); \n</code></pre>\n\n<h2>5. Initiate the uploader in your plugin's JS</h2>\n\n<pre><code> jQuery( document ).ready( function() {\n\n if( jQuery( '.your-plugin-uploader' ).length &gt; 0 ) {\n var options = false;\n var container = jQuery( '.your-plugin-uploader' );\n options = JSON.parse( JSON.stringify( global_uploader_options ) );\n options['multipart_params']['_ajax_nonce'] = container.find( '.ajaxnonce' ).attr( 'id' );\n\n if( container.hasClass( 'multiple' ) ) {\n options['multi_selection'] = true;\n }\n\n var uploader = new plupload.Uploader( options );\n uploader.init();\n\n // EVENTS\n // init\n uploader.bind( 'Init', function( up ) {\n console.log( 'Init', up );\n } );\n\n // file added\n uploader.bind( 'FilesAdded', function( up, files ) {\n jQuery.each( files, function( i, file ) {\n console.log( 'File Added', i, file );\n } );\n\n up.refresh();\n up.start();\n } );\n\n // upload progress\n uploader.bind( 'UploadProgress', function( up, file ) {\n console.log( 'Progress', up, file )\n } );\n\n // file uploaded\n uploader.bind( 'FileUploaded', function( up, file, response ) {\n response = jQuery.parseJSON( response.response );\n\n if( response['status'] == 'success' ) {\n console.log( 'Success', up, file, response );\n } else {\n console.log( 'Error', up, file, response );\n }\n\n } );\n }\n\n } );\n</code></pre>\n" }, { "answer_id": 317745, "author": "Jonas Lundman", "author_id": 43172, "author_profile": "https://wordpress.stackexchange.com/users/43172", "pm_score": 2, "selected": false, "text": "<p>Here is an example for wp version 4.7 and above. The task is simple. This code is directly <strong>cloned</strong> script taken from the <strong>default Wordpress Add new page</strong> (media-new.php).</p>\n\n<pre><code>function my_admin_enqueue_scripts() {\n wp_enqueue_script('plupload-handlers');\n}\nadd_action('admin_enqueue_scripts', 'my_admin_enqueue_scripts');\n</code></pre>\n\n<p>Add this html on your options page. Make shure you keep this <strong>outside your own <code>&lt;form&gt;</code> element</strong>. To keep the variables out of global scope, I recommend to wrap the html output inside a function. This example is lending the top admin notices container to show the area on every admin page... so you can test it without option page.</p>\n\n<pre><code>function my_upload_new_media_html(){\n\n /* everything is copied from media-new.php */\n /* translated, and old browser option is there as well */\n\n $title = __('Upload New Media');\n\n $post_id = 0;\n if(isset($_REQUEST['post_id'])){\n $post_id = absint($_REQUEST['post_id']);\n if(!get_post($post_id) || !current_user_can('edit_post', $post_id)) $post_id = 0;\n }\n\n if($_POST){\n if(isset($_POST['html-upload']) &amp;&amp; !empty($_FILES)){\n check_admin_referer('media-form');\n // Upload File button was clicked\n $upload_id = media_handle_upload('async-upload', $post_id);\n if(is_wp_error($upload_id)){\n wp_die($upload_id);\n }\n }\n wp_redirect(admin_url('upload.php'));\n exit;\n }\n\n $form_class = 'media-upload-form type-form validate';\n if(get_user_setting('uploader') || isset( $_GET['browser-uploader']))\n $form_class .= ' html-uploader';\n\n?&gt;\n\n&lt;div class=\"wrap\"&gt;\n &lt;h1&gt;&lt;?php echo esc_html( $title ); ?&gt;&lt;/h1&gt;\n\n &lt;form enctype=\"multipart/form-data\" method=\"post\" action=\"&lt;?php echo admin_url('media-new.php'); ?&gt;\" class=\"&lt;?php echo esc_attr( $form_class ); ?&gt;\" id=\"file-form\"&gt;\n\n &lt;?php media_upload_form(); ?&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n var post_id = &lt;?php echo $post_id; ?&gt;, shortform = 3;\n &lt;/script&gt;\n &lt;input type=\"hidden\" name=\"post_id\" id=\"post_id\" value=\"&lt;?php echo $post_id; ?&gt;\" /&gt;\n &lt;?php wp_nonce_field('media-form'); ?&gt;\n &lt;div id=\"media-items\" class=\"hide-if-no-js\"&gt;&lt;/div&gt;\n &lt;/form&gt;\n&lt;/div&gt;\n\n&lt;?php\n}\nadd_action('all_admin_notices', 'my_upload_new_media_html');\n</code></pre>\n\n<p>And Boom, its there.</p>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179654", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68312/" ]
When I use Joomla I can change a core string using the language files. So where it would say "Cart" you would go into the language file and change it to what you want it to say. I want to be able to do this for one of our client's websites which uses WordPress. Is this possible? I am using the wpex-adapt theme. The exact bit I want to change is on the Portfolio page on the individual item page where it says "newer" and "older" which I want to change to "previous" and "next". Any suggestions will be greatly appreciated.
Okay, here is what I came up with: It's all about using the [plupload library](http://plupload.com/) that comes shipped with WP. 1. Add a `<div>` to your plugin's option page that later becomes the drag'n'drop area ------------------------------------------------------------------------------------- ``` <div class="your-plugin-uploader multiple"> <input id="your-plugin-uploader-button" type="button" value="<?php esc_attr_e( 'Select Files' ); ?>" class="your-plugin-uploader-button button"> <span class="ajaxnonce" id="<?php echo wp_create_nonce( __FILE__ ); ?>"></span> </div> ``` 2. Register your plugin JS and make sure you define `plupload-all` as a dependency for your script -------------------------------------------------------------------------------------------------- ``` function se179618_admin_js() { wp_register_script( 'your-plugin', WP_PLUGIN_URL . '/your-plugin/js/your-plugin.js', array( 'jquery', 'plupload-all' ) ); } add_action( 'admin_enqueue_scripts', 'se179618_admin_js' ); ``` 3. Write some plupload settings to the page's `<head>` ------------------------------------------------------ ``` function se179618_admin_head() { $uploader_options = array( 'runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => 'my-plugin-uploader-button', 'container' => 'my-plugin-uploader', 'drop_element' => 'my-plugin-uploader', 'file_data_name' => 'async-upload', 'multiple_queues' => true, 'max_file_size' => wp_max_upload_size() . 'b', 'url' => admin_url( 'admin-ajax.php' ), 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ), 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ), 'filters' => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*' ) ), 'multipart' => true, 'urlstream_upload' => true, 'multi_selection' => true, 'multipart_params' => array( '_ajax_nonce' => '', 'action' => 'my-plugin-upload-action' ) ); ?> <script type="text/javascript"> var global_uploader_options=<?php echo json_encode( $uploader_options ); ?>; </script> <?php } add_action( 'admin_head', 'se179618_admin_head' ); ``` 4. Add the action called by the AJAX uploader --------------------------------------------- ``` function se179618_ajax_action() { // check ajax nonce check_ajax_referer( __FILE__ ); if( current_user_can( 'upload_files' ) ) { $response = array(); // handle file upload $id = media_handle_upload( 'async-upload', 0, array( 'test_form' => true, 'action' => 'my-plugin-upload-action' ) ); // send the file' url as response if( is_wp_error( $id ) ) { $response['status'] = 'error'; $response['error'] = $id->get_error_messages(); } else { $response['status'] = 'success'; $src = wp_get_attachment_image_src( $id, 'thumbnail' ); $response['attachment'] = array(); $response['attachment']['id'] = $id; $response['attachment']['src'] = $src[0]; } } echo json_encode( $response ); exit; } add_action( 'wp_ajax_my-plugin-upload-action', 'se179618_ajax_action' ); ``` 5. Initiate the uploader in your plugin's JS -------------------------------------------- ``` jQuery( document ).ready( function() { if( jQuery( '.your-plugin-uploader' ).length > 0 ) { var options = false; var container = jQuery( '.your-plugin-uploader' ); options = JSON.parse( JSON.stringify( global_uploader_options ) ); options['multipart_params']['_ajax_nonce'] = container.find( '.ajaxnonce' ).attr( 'id' ); if( container.hasClass( 'multiple' ) ) { options['multi_selection'] = true; } var uploader = new plupload.Uploader( options ); uploader.init(); // EVENTS // init uploader.bind( 'Init', function( up ) { console.log( 'Init', up ); } ); // file added uploader.bind( 'FilesAdded', function( up, files ) { jQuery.each( files, function( i, file ) { console.log( 'File Added', i, file ); } ); up.refresh(); up.start(); } ); // upload progress uploader.bind( 'UploadProgress', function( up, file ) { console.log( 'Progress', up, file ) } ); // file uploaded uploader.bind( 'FileUploaded', function( up, file, response ) { response = jQuery.parseJSON( response.response ); if( response['status'] == 'success' ) { console.log( 'Success', up, file, response ); } else { console.log( 'Error', up, file, response ); } } ); } } ); ```
179,666
<p>I'm fairly new to Wordpress and am trying to do something very specific. I am currently using <a href="http://html5blank.com/" rel="nofollow">the awesome html5blank</a> to create my custom theme. I am using the native menus for my nav tabs. I am currently using <code>background-image</code>'s to make my nav tabs images instead of text but that is posing problems with what I'm trying to achieve w/ css and making it responsive.</p> <p>I want to be able to add <code>&lt;img&gt;</code> tags( different image for each <code>&lt;li&gt;</code> ) in my <code>&lt;li&gt;</code>'s via HTML.</p> <p>As far as I've been able to find and read up, I need to create a custom structure in this found in my <code>function.php</code> file?</p> <pre><code>function html5blank_nav() { wp_nav_menu( array( 'theme_location' =&gt; 'header-menu', 'menu' =&gt; '', 'container' =&gt; 'div', 'container_class' =&gt; 'menu-{menu slug}-container', 'container_id' =&gt; '', 'menu_class' =&gt; 'menu', 'menu_id' =&gt; '', 'echo' =&gt; true, 'fallback_cb' =&gt; 'wp_page_menu', 'before' =&gt; '', 'after' =&gt; '', 'link_before' =&gt; '', 'link_after' =&gt; '', 'items_wrap' =&gt; '&lt;ul&gt;%3$s&lt;/ul&gt;', 'depth' =&gt; 0, 'walker' =&gt; '' ) ); } </code></pre> <p>Please let me know what else I need to provide to make this question make more sense and help you get me on the right track. Thanks in advance. </p>
[ { "answer_id": 179673, "author": "Travis Seitler", "author_id": 49522, "author_profile": "https://wordpress.stackexchange.com/users/49522", "pm_score": 3, "selected": true, "text": "<p>Given the amount of customization you're looking to make, your best bet may be to integrate a custom Walker function. From <a href=\"http://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function\" rel=\"nofollow\">the Codex</a>:</p>\n\n<blockquote>\n <p>For deeper conditional classes, you'll need to use a custom walker function (created in the <code>'walker' =&gt; new Your_Walker_Function</code> argument).</p>\n \n <p>The easiest way to build a new walker function is to copy the default class (Walker_Nav_Menu) from <code>\\wp-includes\\nav-menu-template.php</code> and simply customize what you need.</p>\n</blockquote>\n\n<p>Using a custom Walker gives you a wide degree of flexibility and control that the <code>wp_nav_menu()</code> function just doesn't allow for in and of itself. It enables you to not just reformat the output of menu items, but now you're able to run all manner of code during the menu building process.</p>\n\n<p>In a nutshell, what you'd do is:</p>\n\n<ol>\n<li>Copy/Paste the code for the <code>Walker_Nav_Menu</code> class from into your theme's <code>functions.php</code> file;</li>\n<li>Edit the top line to something like <code>class My_HTML5Blank_Walker_Nav_Menu extends Walker_Nav_Menu</code>;</li>\n<li>Insert all the new code for building image tag references in the <code>start_el</code> public function;</li>\n<li>Modify the last line of your <code>wp_nav_menu</code> code to point to your new custom Walker, i.e. <code>'walker' =&gt; 'My_HTML5Blank_Walker_Nav_Menu'</code>.</li>\n</ol>\n\n<p>Now, the <strong>way</strong> you decide to integrate those images is entirely up to you... but check this out: if the menu items are posts/pages/categories, etc. (i.e., not custom/manual links), then using the custom Walker means you can pull in each post/page/term object's metadata and use <em>that</em> to alter the menu output. (In other words, you can set a featured image for a post, then using a custom Walker you can <em>grab the metadata for that post</em> and embed its associated featured image thumbnail!)</p>\n\n<p>Anyway, hopefully I gave you enough to get started here. Let me know if I missed anything (or if there's something confusing here that you'd like me to clear up).</p>\n" }, { "answer_id": 245830, "author": "Rahul Gupta", "author_id": 106779, "author_profile": "https://wordpress.stackexchange.com/users/106779", "pm_score": 0, "selected": false, "text": "<p>The code I am providing here can be modified to display the custom menu.</p>\n\n<p>My custom structure for menu is like:</p>\n\n<pre><code>&lt;ul class=\"navigation\"&gt;\n &lt;li class=\"active\"&gt;\n &lt;a href=\"item1.html\"&gt;Menu item 1&lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a href=\"item2.html\"&gt;Menu item 2&lt;/a&gt;\n &lt;/li&gt;\n\n &lt;li&gt;\n &lt;a href=\"item3.html\"&gt;Menu item 3&lt;/a&gt;\n &lt;div&gt;\n &lt;a href=\"subitem1.html\"&gt;Sub Menu item 1&lt;/a&gt;\n &lt;a href=\"subitem2.html\"&gt;Sub Menu item 2&lt;/a&gt;\n &lt;/div&gt;\n &lt;/li&gt;\n\n&lt;/ul&gt;\n</code></pre>\n\n<p>So to build such a custom layout for my displaying my menu, I used the code below:</p>\n\n<pre><code>&lt;ul class=\"navigation\"&gt;\n&lt;?php\n$count = 0;\n$submenu = false;\n\nforeach( $menuitems as $item ) {\n $link = $item-&gt;url;\n $title = $item-&gt;title;\n // item does not have a parent so menu_item_parent equals 0 (false)\n if ( !$item-&gt;menu_item_parent ) {\n // save this id for later comparison with sub-menu items\n $parent_id = $item-&gt;ID;\n\n if ($getCurrenturl == $link) {\n $activeClass = 'active';\n } else {\n $activeClass = '';\n }\n ?&gt;\n &lt;li class=\"item &lt;?php echo $activeClass; ?&gt;\"&gt;\n &lt;a href=\"&lt;?php echo $link; ?&gt;\" class=\"title\"&gt;&lt;?php echo $title; ?&gt;&lt;/a&gt;\n &lt;?php \n } \n\n if ( $parent_id == $item-&gt;menu_item_parent ) {\n if ( !$submenu ) {\n $submenu = true; \n ?&gt;\n &lt;div&gt;\n &lt;?php } ?&gt;\n\n &lt;a href=\"&lt;?php echo $link; ?&gt;\" class=\"title\"&gt;&lt;?php echo $title; ?&gt;&lt;/a&gt;\n\n &lt;?php if ( $menuitems[ $count + 1 ]-&gt;menu_item_parent != $parent_id &amp;&amp; $submenu ) { ?&gt;\n &lt;/div&gt;\n &lt;?php \n $submenu = false; \n }\n }\n ?&gt;\n\n&lt;?php if ( $menuitems[ $count + 1 ]-&gt;menu_item_parent != $parent_id ) { ?&gt;\n&lt;/li&gt; \n&lt;?php \n $submenu = false; \n} \n?&gt;\n\n&lt;?php \n$count++; \n} \n?&gt;\n\n&lt;/ul&gt;\n</code></pre>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60779/" ]
I'm fairly new to Wordpress and am trying to do something very specific. I am currently using [the awesome html5blank](http://html5blank.com/) to create my custom theme. I am using the native menus for my nav tabs. I am currently using `background-image`'s to make my nav tabs images instead of text but that is posing problems with what I'm trying to achieve w/ css and making it responsive. I want to be able to add `<img>` tags( different image for each `<li>` ) in my `<li>`'s via HTML. As far as I've been able to find and read up, I need to create a custom structure in this found in my `function.php` file? ``` function html5blank_nav() { wp_nav_menu( array( 'theme_location' => 'header-menu', 'menu' => '', 'container' => 'div', 'container_class' => 'menu-{menu slug}-container', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul>%3$s</ul>', 'depth' => 0, 'walker' => '' ) ); } ``` Please let me know what else I need to provide to make this question make more sense and help you get me on the right track. Thanks in advance.
Given the amount of customization you're looking to make, your best bet may be to integrate a custom Walker function. From [the Codex](http://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function): > > For deeper conditional classes, you'll need to use a custom walker function (created in the `'walker' => new Your_Walker_Function` argument). > > > The easiest way to build a new walker function is to copy the default class (Walker\_Nav\_Menu) from `\wp-includes\nav-menu-template.php` and simply customize what you need. > > > Using a custom Walker gives you a wide degree of flexibility and control that the `wp_nav_menu()` function just doesn't allow for in and of itself. It enables you to not just reformat the output of menu items, but now you're able to run all manner of code during the menu building process. In a nutshell, what you'd do is: 1. Copy/Paste the code for the `Walker_Nav_Menu` class from into your theme's `functions.php` file; 2. Edit the top line to something like `class My_HTML5Blank_Walker_Nav_Menu extends Walker_Nav_Menu`; 3. Insert all the new code for building image tag references in the `start_el` public function; 4. Modify the last line of your `wp_nav_menu` code to point to your new custom Walker, i.e. `'walker' => 'My_HTML5Blank_Walker_Nav_Menu'`. Now, the **way** you decide to integrate those images is entirely up to you... but check this out: if the menu items are posts/pages/categories, etc. (i.e., not custom/manual links), then using the custom Walker means you can pull in each post/page/term object's metadata and use *that* to alter the menu output. (In other words, you can set a featured image for a post, then using a custom Walker you can *grab the metadata for that post* and embed its associated featured image thumbnail!) Anyway, hopefully I gave you enough to get started here. Let me know if I missed anything (or if there's something confusing here that you'd like me to clear up).
179,667
<p>We have the site from <a href="http://asceticexperience.com/" rel="nofollow">http://asceticexperience.com/</a></p> <p>Feel free to dig the site in order to understand our question below.</p> <p>Of course, any feedback appreciated :-) but my main question is the following:</p> <p>We have a photo multiple times on site (in blog, portfolio, and in slide-shows from the menus Body, Mind, Heart).</p> <p>The description of the photos is taken from 'Description' field from Media Gallery. (As you know the field is filled from photo's EXIF).</p> <p>Because each time when I attach a photo to a page/post, WordPress copies the photo, we need a plugin/solution/whatever to allow us to change simultaneously the description of all the instances for the eg. myPhoto.jpg.</p> <p>Now when we want to change/update a caption, we need to go to all instances and manually edit them.</p> <p>Does someone knows a solution for this problem?</p>
[ { "answer_id": 179669, "author": "Nathan", "author_id": 11952, "author_profile": "https://wordpress.stackexchange.com/users/11952", "pm_score": 1, "selected": false, "text": "<p>I'm guessing you're referring to images which have been placed into WordPress' post content editor, right?</p>\n\n<p>For example, you clicked \"Add Media\" and then uploaded a photo and inserted it into your post. What's hard to know is whether you're actually referring to a \"Description\" or if you mean the \"Alt Text\", \"Caption\" or \"Title\" fields. I have never seen the actual \"Description\" field get filled by default, from EXIF or otherwise, though I have seen the \"Title\" field get auto-populated. </p>\n\n<p>Either way, if you're referring to images you've placed directly into your post's content, you can't easily edit this information. It's more or less hard-coded HTML in the post and updating any of the \"Title\", \"Caption\", \"Alt Text\" or \"Description\" fields in the Media Editor will not update this in post content editors.</p>\n\n<p>However, there are a couple of solutions available to you. </p>\n\n<p>If you can login to PHPMyAdmin, you can do a global search and replace. As with anything \"messing with your database\" related, <strong>make a backup first!</strong></p>\n\n<ol>\n<li>In PHPMyAdmin, select the database you want to work with from the list on the left</li>\n<li>Click on \"SQL\" in the list of tabs at the top.</li>\n<li><p>Enter the following query</p>\n\n<p><code>UPDATE `wp_posts` SET `post_content` = replace(`post_content`, 'this is your original description1234567890', 'this is the new one')</code></p></li>\n<li><p>Click Go</p></li>\n</ol>\n\n<p>I just tested this and had no issue with my site, but for real for reals, do the whole backup thing first.</p>\n\n<p>There's also this plugin but it's not done all that well for me in the past: <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">https://wordpress.org/plugins/search-and-replace/</a></p>\n" }, { "answer_id": 179689, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<h2>Plugin idea #1</h2>\n\n<p>When we insert an image into the editor, the plugin automatically modifies the <em>caption</em> and the <em>alt</em> attribute to:</p>\n\n<pre><code>[caption id=\"attachment_729\" align=\"alignnone\" width=\"300\"]\n &lt;a href=\"http://example.tld/wp-content/uploads/2015/02/wordpress.jpg\"&gt;\n &lt;img src=\"http://example.tld/wp-content/uploads/2015/02/wordpress-300x284.jpg\" \n alt=\"###ALT###\" \n width=\"300\" \n height=\"284\" \n class=\"size-medium wp-image-729\" /&gt;\n &lt;/a&gt; \n ###CAPTION###\n[/caption]\n</code></pre>\n\n<p>Then on the front-end the image caption is fetched for the corresponding image attachment, based on the <code>attachment_729</code> string and replaces the <code>###ALT###</code> and <code>###CAPTION###</code> dummy values.</p>\n\n<p>So when we want to modify the captions for all the image copies, we only have to do it once in the Media Manager.</p>\n\n<p>Here's our <em>Dynamic Image Caption</em> plugin that should support this feature (PHP 5.4+):</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Dynamic Image Caption #1\n * Description: We only want to modify the image captions in the Media Manager \n * Plugin URI: http://wordpress.stackexchange.com/a/179689/26350\n * Plugin Author: Birgir Erlendsson (birgire)\n * Version: 0.0.1\n */\n\nnamespace birgire\\wpse;\n\nadd_action( 'init', function()\n{\n $o = new DynamicImageCaption;\n $o-&gt;activate();\n});\n\nclass DynamicImageCaption\n{\n private $caption_dummy = '###CAPTION###';\n private $alt_dummy = '###ALT###';\n\n public function activate()\n {\n add_shortcode( \n 'caption', \n [ $this, 'caption_shortcode' ] \n );\n\n add_filter( \n 'image_add_caption_text', \n [ $this, 'add_caption_text' ], \n 10, \n 2 \n );\n\n add_filter( \n 'image_send_to_editor', \n [ $this, 'send_to_editor' ],\n 10, \n 8 \n );\n }\n\n public function caption_shortcode( $attr = [], $content = '' )\n {\n if( isset( $attr['id'] ) \n &amp;&amp; ( \n false !== strpos( $content, $this-&gt;caption_dummy ) \n ||\n false !== strpos( $content, $this-&gt;alt_dummy ) \n )\n )\n {\n $caption = $this-&gt;get_caption( \n $attr['id'], \n str_replace( 'attachment_', '', $attr['id'] ) \n );\n\n $content = str_replace(\n [ $this-&gt;caption_dummy, $this-&gt;alt_dummy ],\n [ $caption, esc_attr( $caption ) ],\n $content\n );\n }\n return img_caption_shortcode( $attr, $content );\n }\n\n private function get_caption( $caption, $id )\n {\n $caption = '';\n\n $attachments = get_posts( \n [ \n 'p' =&gt; $id, \n 'post_type' =&gt; 'attachment', \n 'post_status' =&gt; 'inherit' \n ] \n );\n\n if( isset( $attachments[0] ) \n &amp;&amp; $attachments[0] instanceof \\WP_Post \n )\n $caption = $attachments[0]-&gt;post_excerpt;\n\n return $caption;\n }\n\n public function send_to_editor( $html, $id, $caption, $title, $align, $url, $size, $alt )\n {\n if( $alt )\n {\n $html = str_replace(\n 'alt=\"' . esc_attr( $alt ),\n 'alt=\"' . $this-&gt;alt_dummy,\n $html\n );\n }\n return $html;\n }\n\n} // end class\n</code></pre>\n\n<p>Copy this into the file: </p>\n\n<pre><code>/wp-content/plugins/dynamic-image-caption/dynamic-image-caption.php\n</code></pre>\n\n<p>and activate the plugin. </p>\n\n<p>Note that here I use the <em>caption</em> also as the <em>alt</em> attribute for convenience. You should test this further and modify to your needs.</p>\n\n<p>Ps: My first idea was to add extra shortcodes within the <code>[caption]</code> shortcode, like:</p>\n\n<pre><code>[dynamic_caption id=\"729\"] \n</code></pre>\n\n<p>and </p>\n\n<pre><code>[dynamic_alt id=\"729\"] \n</code></pre>\n\n<p>This works, but I wanted to find another way that only fetches the corresponding attachment once, without using these kind of shortcodes.</p>\n\n<h2>Plugin idea #2</h2>\n\n<p>Here's another idea to modify the existing image captions and alt attributes. This plugin doesn't modify the code in the post editor, like the previous plugin did, only it's output.</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Dynamic Image Caption And Alt #2\n * Description: We only want to modify the image caption and alt in the Media Manager. \n * Plugin URI: http://wordpress.stackexchange.com/a/179689/26350\n * Plugin Author: Birgir Erlendsson (birgire)\n * Version: 0.0.1\n */\n\nnamespace birgire\\wpse;\n\nadd_action( 'init', function()\n{\n $o = new DynamicImageCaptionAlt;\n $o-&gt;activate();\n});\n\nclass DynamicImageCaptionAlt\n{\n public function activate()\n {\n add_shortcode( \n 'caption', \n [ $this, 'caption_shortcode' ] \n );\n }\n\n public function caption_shortcode( $attr = [], $content = '' )\n {\n if( isset( $attr['id'] ) )\n {\n $id = str_replace( 'attachment_', '', $attr['id'] );\n\n // Fetch the caption and the alt attribute:\n $caption = $this-&gt;get_caption( $id );\n $alt = esc_attr( $this-&gt;get_alt( $id ) );\n\n // Use caption as alt, if alt is empty:\n if( ! $alt )\n $alt = esc_attr( $caption );\n\n // Modify the caption:\n $content .= '###END###';\n $content = str_replace( \n strip_tags( $content ), \n $caption, \n $content \n );\n\n // Modify the alt attribute:\n $content = preg_replace( \n '#alt=\"[^\"]*\"#', \n sprintf( 'alt=\"%s\"', $alt ), \n $content \n );\n }\n return img_caption_shortcode( $attr, $content );\n }\n\n private function get_caption( $id )\n {\n global $wpdb;\n $sql = $wpdb-&gt;prepare( \n \"SELECT post_excerpt \n FROM {$wpdb-&gt;posts} \n WHERE ID = %d AND post_type = 'attachment' \", \n $id \n );\n return $wpdb-&gt;get_var( $sql );\n }\n\n private function get_alt( $id )\n {\n return get_post_meta( $id, '_wp_attachment_image_alt', true );\n }\n\n} // end class\n</code></pre>\n\n<p>Note that this will add extra database queries to your site, as expected. </p>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1198/" ]
We have the site from <http://asceticexperience.com/> Feel free to dig the site in order to understand our question below. Of course, any feedback appreciated :-) but my main question is the following: We have a photo multiple times on site (in blog, portfolio, and in slide-shows from the menus Body, Mind, Heart). The description of the photos is taken from 'Description' field from Media Gallery. (As you know the field is filled from photo's EXIF). Because each time when I attach a photo to a page/post, WordPress copies the photo, we need a plugin/solution/whatever to allow us to change simultaneously the description of all the instances for the eg. myPhoto.jpg. Now when we want to change/update a caption, we need to go to all instances and manually edit them. Does someone knows a solution for this problem?
Plugin idea #1 -------------- When we insert an image into the editor, the plugin automatically modifies the *caption* and the *alt* attribute to: ``` [caption id="attachment_729" align="alignnone" width="300"] <a href="http://example.tld/wp-content/uploads/2015/02/wordpress.jpg"> <img src="http://example.tld/wp-content/uploads/2015/02/wordpress-300x284.jpg" alt="###ALT###" width="300" height="284" class="size-medium wp-image-729" /> </a> ###CAPTION### [/caption] ``` Then on the front-end the image caption is fetched for the corresponding image attachment, based on the `attachment_729` string and replaces the `###ALT###` and `###CAPTION###` dummy values. So when we want to modify the captions for all the image copies, we only have to do it once in the Media Manager. Here's our *Dynamic Image Caption* plugin that should support this feature (PHP 5.4+): ``` <?php /** * Plugin Name: Dynamic Image Caption #1 * Description: We only want to modify the image captions in the Media Manager * Plugin URI: http://wordpress.stackexchange.com/a/179689/26350 * Plugin Author: Birgir Erlendsson (birgire) * Version: 0.0.1 */ namespace birgire\wpse; add_action( 'init', function() { $o = new DynamicImageCaption; $o->activate(); }); class DynamicImageCaption { private $caption_dummy = '###CAPTION###'; private $alt_dummy = '###ALT###'; public function activate() { add_shortcode( 'caption', [ $this, 'caption_shortcode' ] ); add_filter( 'image_add_caption_text', [ $this, 'add_caption_text' ], 10, 2 ); add_filter( 'image_send_to_editor', [ $this, 'send_to_editor' ], 10, 8 ); } public function caption_shortcode( $attr = [], $content = '' ) { if( isset( $attr['id'] ) && ( false !== strpos( $content, $this->caption_dummy ) || false !== strpos( $content, $this->alt_dummy ) ) ) { $caption = $this->get_caption( $attr['id'], str_replace( 'attachment_', '', $attr['id'] ) ); $content = str_replace( [ $this->caption_dummy, $this->alt_dummy ], [ $caption, esc_attr( $caption ) ], $content ); } return img_caption_shortcode( $attr, $content ); } private function get_caption( $caption, $id ) { $caption = ''; $attachments = get_posts( [ 'p' => $id, 'post_type' => 'attachment', 'post_status' => 'inherit' ] ); if( isset( $attachments[0] ) && $attachments[0] instanceof \WP_Post ) $caption = $attachments[0]->post_excerpt; return $caption; } public function send_to_editor( $html, $id, $caption, $title, $align, $url, $size, $alt ) { if( $alt ) { $html = str_replace( 'alt="' . esc_attr( $alt ), 'alt="' . $this->alt_dummy, $html ); } return $html; } } // end class ``` Copy this into the file: ``` /wp-content/plugins/dynamic-image-caption/dynamic-image-caption.php ``` and activate the plugin. Note that here I use the *caption* also as the *alt* attribute for convenience. You should test this further and modify to your needs. Ps: My first idea was to add extra shortcodes within the `[caption]` shortcode, like: ``` [dynamic_caption id="729"] ``` and ``` [dynamic_alt id="729"] ``` This works, but I wanted to find another way that only fetches the corresponding attachment once, without using these kind of shortcodes. Plugin idea #2 -------------- Here's another idea to modify the existing image captions and alt attributes. This plugin doesn't modify the code in the post editor, like the previous plugin did, only it's output. ``` <?php /** * Plugin Name: Dynamic Image Caption And Alt #2 * Description: We only want to modify the image caption and alt in the Media Manager. * Plugin URI: http://wordpress.stackexchange.com/a/179689/26350 * Plugin Author: Birgir Erlendsson (birgire) * Version: 0.0.1 */ namespace birgire\wpse; add_action( 'init', function() { $o = new DynamicImageCaptionAlt; $o->activate(); }); class DynamicImageCaptionAlt { public function activate() { add_shortcode( 'caption', [ $this, 'caption_shortcode' ] ); } public function caption_shortcode( $attr = [], $content = '' ) { if( isset( $attr['id'] ) ) { $id = str_replace( 'attachment_', '', $attr['id'] ); // Fetch the caption and the alt attribute: $caption = $this->get_caption( $id ); $alt = esc_attr( $this->get_alt( $id ) ); // Use caption as alt, if alt is empty: if( ! $alt ) $alt = esc_attr( $caption ); // Modify the caption: $content .= '###END###'; $content = str_replace( strip_tags( $content ), $caption, $content ); // Modify the alt attribute: $content = preg_replace( '#alt="[^"]*"#', sprintf( 'alt="%s"', $alt ), $content ); } return img_caption_shortcode( $attr, $content ); } private function get_caption( $id ) { global $wpdb; $sql = $wpdb->prepare( "SELECT post_excerpt FROM {$wpdb->posts} WHERE ID = %d AND post_type = 'attachment' ", $id ); return $wpdb->get_var( $sql ); } private function get_alt( $id ) { return get_post_meta( $id, '_wp_attachment_image_alt', true ); } } // end class ``` Note that this will add extra database queries to your site, as expected.
179,683
<p>I stupidly created a ton of websites with custom themes (not child themes, 100% custom) and named my theme folder "custom". Now they are starting to auto-update and get replaced with some theme from the repository that happens to use the same folder name.</p> <p>I could disable the updates in wp_config, but I don't really like that idea. Isn't there something I can do just in my theme files, to tell WordPress "this is a totally custom theme, not on your repository, don't try to update it"? This info must be around, but I just can't find it. I tried setting a name in my style.css file, but that didn't help, WordPress is still saying "update available" (and will overwrite my files if I click that option).</p> <p>I usually just don't give my themes a name, my style.css file just starts out with my actual CSS.. and it seems to work fine, until this issue started.</p> <p>If I rename the folder to something more obscure, that works... but then I'll have to recreate my menus, and not sure what else, because WP thinks I switched themes if I do that.</p> <p>Maybe some tag I can add to style.css? Something like a "slug" or update URL?</p>
[ { "answer_id": 179684, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 4, "selected": true, "text": "<p>If the theme slug matches, but you have no version number in the style.css file (even if Name is missing too), it will always try to update that theme. The easiest way to prevent this is to add a Version in the style.css header and set it to a really high number that is unlikely to be lower than that theme's version:</p>\n\n<pre><code>/*\nVersion: 999\n*/\n</code></pre>\n" }, { "answer_id": 326630, "author": "amit kumar", "author_id": 159826, "author_profile": "https://wordpress.stackexchange.com/users/159826", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('after_setup_theme','remove_core_updates');\nfunction remove_core_updates(){\n\n if(! current_user_can('update_core')){\n return;\n }\n\n add_action('init', create_function('$a',\"remove_action( 'init', 'wp_version_check' );\"),2);\n add_filter('pre_option_update_core','__return_null');\n add_filter('pre_site_transiAent_update_core','__return_null');\n}\n</code></pre>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41149/" ]
I stupidly created a ton of websites with custom themes (not child themes, 100% custom) and named my theme folder "custom". Now they are starting to auto-update and get replaced with some theme from the repository that happens to use the same folder name. I could disable the updates in wp\_config, but I don't really like that idea. Isn't there something I can do just in my theme files, to tell WordPress "this is a totally custom theme, not on your repository, don't try to update it"? This info must be around, but I just can't find it. I tried setting a name in my style.css file, but that didn't help, WordPress is still saying "update available" (and will overwrite my files if I click that option). I usually just don't give my themes a name, my style.css file just starts out with my actual CSS.. and it seems to work fine, until this issue started. If I rename the folder to something more obscure, that works... but then I'll have to recreate my menus, and not sure what else, because WP thinks I switched themes if I do that. Maybe some tag I can add to style.css? Something like a "slug" or update URL?
If the theme slug matches, but you have no version number in the style.css file (even if Name is missing too), it will always try to update that theme. The easiest way to prevent this is to add a Version in the style.css header and set it to a really high number that is unlikely to be lower than that theme's version: ``` /* Version: 999 */ ```
179,694
<p>I write Following code to run my function every day at 16:20 .. </p> <p>But I guess is the problem in code..</p> <p>not working </p> <p>Epoch timestamp: 1427488800 </p> <p>3/28/2015 1:10:00 AM</p> <pre><code>if( !wp_next_scheduled( 'import_into_db' ) ) { wp_schedule_event( time('1427488800'), 'daily', 'import_into_db' ); function import_into_db(){ ////My code } add_action('wp', 'import_into_db'); } </code></pre>
[ { "answer_id": 179699, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 2, "selected": false, "text": "<p>Well, 1427488800 resolves to March 27, 2015, so your event isn't even set to start yet.</p>\n\n<p>Also, bear in mind that scheduled WP events will only fire if someone hits the site at that time.</p>\n" }, { "answer_id": 179774, "author": "amir rasabeh", "author_id": 67818, "author_profile": "https://wordpress.stackexchange.com/users/67818", "pm_score": 6, "selected": true, "text": "<p>WP Cron runs, when somebody visits your website.\nThus if nobody visits, the cron never runs.</p>\n\n<p>Now there are 2 solutions:</p>\n\n<ol>\n<li>Disable WP Cron, use a real cron job and customize it.</li>\n</ol>\n\n<p><a href=\"https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job\" rel=\"noreferrer\">https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job</a></p>\n\n<ol start=\"2\">\n<li><p>Use a custom interval in <code>wp_schedule_event()</code>:</p>\n\n<pre><code>function myprefix_custom_cron_schedule( $schedules ) {\n $schedules['every_six_hours'] = array(\n 'interval' =&gt; 21600, // Every 6 hours\n 'display' =&gt; __( 'Every 6 hours' ),\n );\n return $schedules;\n}\nadd_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' );\n\n//Schedule an action if it's not already scheduled\nif ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) {\n wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' );\n}\n\n///Hook into that action that'll fire every six hours\n add_action( 'myprefix_cron_hook', 'myprefix_cron_function' );\n\n//create your function, that runs on cron\nfunction myprefix_cron_function() {\n //your function...\n}\n</code></pre></li>\n</ol>\n\n<p>and you can see these tuts</p>\n\n<p><a href=\"http://www.nextscripts.com/tutorials/wp-cron-scheduling-tasks-in-wordpress/\" rel=\"noreferrer\">http://www.nextscripts.com/tutorials/wp-cron-scheduling-tasks-in-wordpress/</a></p>\n\n<p><a href=\"http://www.iceablethemes.com/optimize-wordpress-replace-wp_cron-real-cron-job/\" rel=\"noreferrer\">http://www.iceablethemes.com/optimize-wordpress-replace-wp_cron-real-cron-job/</a></p>\n\n<p><a href=\"http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/\" rel=\"noreferrer\">http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/</a></p>\n\n<p>custom Wp cron </p>\n\n<p><a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules\" rel=\"noreferrer\">http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules</a></p>\n\n<p><a href=\"http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/\" rel=\"noreferrer\">http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/</a></p>\n\n<p><a href=\"http://www.viper007bond.com/2011/12/14/how-to-create-custom-wordpress-cron-intervals/\" rel=\"noreferrer\">http://www.viper007bond.com/2011/12/14/how-to-create-custom-wordpress-cron-intervals/</a></p>\n\n<p><a href=\"http://www.sitepoint.com/mastering-wordpress-cron/\" rel=\"noreferrer\">http://www.sitepoint.com/mastering-wordpress-cron/</a></p>\n\n<p><a href=\"https://tommcfarlin.com/wordpress-cron-jobs/\" rel=\"noreferrer\">https://tommcfarlin.com/wordpress-cron-jobs/</a></p>\n\n<p><a href=\"http://www.paulund.co.uk/create-cron-jobs-in-wordpress\" rel=\"noreferrer\">http://www.paulund.co.uk/create-cron-jobs-in-wordpress</a></p>\n\n<p>cron linux </p>\n\n<p><a href=\"http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/\" rel=\"noreferrer\">http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/</a></p>\n\n<p><a href=\"http://www.thesitewizard.com/general/set-cron-job.shtml\" rel=\"noreferrer\">http://www.thesitewizard.com/general/set-cron-job.shtml</a></p>\n\n<p><a href=\"http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800\" rel=\"noreferrer\">http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800</a></p>\n\n<p><a href=\"https://www.google.com/search?q=wp%20cron%20job%20wih%20real%20cron%20job&amp;oq=wp%20cron%20job%20wih%20real%20cron%20job&amp;aqs=chrome..69i57j69i64.21049j0j1&amp;sourceid=chrome&amp;es_sm=122&amp;ie=UTF-8#safe=active&amp;q=wp%20cron%20job%20with%20real%20cron%20job&amp;spell=1\" rel=\"noreferrer\">google search</a></p>\n" }, { "answer_id": 200229, "author": "Goran Jakovljevic", "author_id": 15469, "author_profile": "https://wordpress.stackexchange.com/users/15469", "pm_score": 5, "selected": false, "text": "<p>Instead of <a href=\"http://php.net/manual/en/function.time.php\" rel=\"noreferrer\">time()</a>, use <a href=\"http://php.net/manual/en/function.strtotime.php\" rel=\"noreferrer\">strtotime()</a> function so you can specify the time of day - it will use today's date with the time that you specify. So in your case:</p>\n\n<pre><code>strtotime('16:20:00'); // 4:20 PM\n</code></pre>\n\n<p>Usage in the <code>wp_schedule_event</code> function would look like this:</p>\n\n<pre><code>wp_schedule_event( strtotime('16:20:00'), 'daily', 'import_into_db' );\n</code></pre>\n" }, { "answer_id": 299877, "author": "Rob P", "author_id": 93167, "author_profile": "https://wordpress.stackexchange.com/users/93167", "pm_score": 2, "selected": false, "text": "<p>This code is working for me, I believe it is closer to the original question. You want to get the UNIX time + timezone for when you want it to execute. Once the cron executes and is removed from WP, it recreates itself at the time you specify.</p>\n\n<p>In the following example, I have it working for AEST (GMT+10) @ 6AM each morning. So I am scheduling it for GMT 20:00 each day.</p>\n\n<pre><code>if (!wp_next_scheduled('cron_name')) {\n $time = strtotime('today'); //returns today midnight\n $time = $time + 72000; //add an offset for the time of day you want, keeping in mind this is in GMT.\n wp_schedule_event($time, 'daily', 'cron_name');\n}\n</code></pre>\n" } ]
2015/02/27
[ "https://wordpress.stackexchange.com/questions/179694", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48589/" ]
I write Following code to run my function every day at 16:20 .. But I guess is the problem in code.. not working Epoch timestamp: 1427488800 3/28/2015 1:10:00 AM ``` if( !wp_next_scheduled( 'import_into_db' ) ) { wp_schedule_event( time('1427488800'), 'daily', 'import_into_db' ); function import_into_db(){ ////My code } add_action('wp', 'import_into_db'); } ```
WP Cron runs, when somebody visits your website. Thus if nobody visits, the cron never runs. Now there are 2 solutions: 1. Disable WP Cron, use a real cron job and customize it. <https://support.hostgator.com/articles/specialized-help/technical/wordpress/how-to-replace-wordpress-cron-with-a-real-cron-job> 2. Use a custom interval in `wp_schedule_event()`: ``` function myprefix_custom_cron_schedule( $schedules ) { $schedules['every_six_hours'] = array( 'interval' => 21600, // Every 6 hours 'display' => __( 'Every 6 hours' ), ); return $schedules; } add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' ); //Schedule an action if it's not already scheduled if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) { wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' ); } ///Hook into that action that'll fire every six hours add_action( 'myprefix_cron_hook', 'myprefix_cron_function' ); //create your function, that runs on cron function myprefix_cron_function() { //your function... } ``` and you can see these tuts <http://www.nextscripts.com/tutorials/wp-cron-scheduling-tasks-in-wordpress/> <http://www.iceablethemes.com/optimize-wordpress-replace-wp_cron-real-cron-job/> <http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/> custom Wp cron <http://codex.wordpress.org/Plugin_API/Filter_Reference/cron_schedules> <http://www.smashingmagazine.com/2013/10/16/schedule-events-using-wordpress-cron/> <http://www.viper007bond.com/2011/12/14/how-to-create-custom-wordpress-cron-intervals/> <http://www.sitepoint.com/mastering-wordpress-cron/> <https://tommcfarlin.com/wordpress-cron-jobs/> <http://www.paulund.co.uk/create-cron-jobs-in-wordpress> cron linux <http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/> <http://www.thesitewizard.com/general/set-cron-job.shtml> <http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800> [google search](https://www.google.com/search?q=wp%20cron%20job%20wih%20real%20cron%20job&oq=wp%20cron%20job%20wih%20real%20cron%20job&aqs=chrome..69i57j69i64.21049j0j1&sourceid=chrome&es_sm=122&ie=UTF-8#safe=active&q=wp%20cron%20job%20with%20real%20cron%20job&spell=1)
179,713
<p>I spent hours trying to find a solution to this, but I am not able to figure it out. I have a table that shows user's data and I am trying to add pagination to it.</p> <p>I have tried by adding "paged" in the array but when I click on the link I get "Page not found".</p> <p>If I understand correctly the problem is created due to the fact that I have a table generated instead of "calling" posts.</p> <p>Here's what I have now:</p> <pre><code> &lt;?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'deal_admin' ) ) ): ?&gt; &lt;div class="dashboard_container section main_block"&gt; &lt;?php // Purchase history if ( gb_account_merchant_id() ) { $deals = null; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; gb_get_deal_post_type(), 'post__in' =&gt; gb_get_merchants_deal_ids(gb_account_merchant_id()), 'post_status' =&gt; 'publish', 'gb_bypass_filter' =&gt; TRUE, 'posts_per_page' =&gt; 5, // return this many 'paged' =&gt; $paged, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; gb_get_deal_cat_slug(), 'field' =&gt; 'id', 'terms' =&gt; array( 81,82,83,84,85,86,87,88,89,90,91,92 ), 'operator' =&gt; 'NOT IN', ), ), ); if ( isset( $_GET['filter'] ) &amp;&amp; $_GET['filter'] != '-1' ) { $args['tax_query'][] = array( 'taxonomy' =&gt; gb_get_deal_cat_slug(), 'field' =&gt; 'id', 'terms' =&gt; array( $_GET['filter'] ), ); } $deals = new WP_Query($args); if ($deals-&gt;have_posts()) { ?&gt; &lt;?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin' ) ) ): ?&gt; &lt;span class="specialLink_here" style="font-size:16px;"&gt;&lt;a href="&lt;?php gb_merchant_purchases_report_url( gb_account_merchant_id() ) ?&gt;" class="report_button"&gt;&lt;?php gb_e('Purchase History') ?&gt;&lt;/a&gt; | &lt;/span&gt; &lt;?php if ( function_exists( 'gb_sales_summary_report_url' ) ): ?&gt; &lt;span class="specialLink_here" style="font-size:16px;"&gt;&lt;a href="&lt;?php gb_sales_summary_report_url() ?&gt;" class="report_button"&gt;&lt;?php gb_e('Sales Summary Report') ?&gt;&lt;/a&gt; | &lt;/span&gt; &lt;?php endif ?&gt; &lt;?php endif ?&gt; &lt;?php if ( !function_exists('gb_is_user_merchant_role') || gb_is_user_merchant_role( array( 'merchant_admin', 'sales_admin' ) ) ): ?&gt; &lt;?php if ( function_exists( 'sec_get_users_report_url' ) ): ?&gt; &lt;span class="specialLink_here" style="font-size:16px;"&gt;&lt;a href="&lt;?php echo sec_get_users_report_url() ?&gt;" class="report_button"&gt;&lt;?php gb_e('Customer Report') ?&gt;&lt;/a&gt;&lt;/span&gt; &lt;?php endif ?&gt; &lt;?php endif ?&gt; &lt;table class="report_table merchant_dashboard" style="margin-top:20px;"&gt;&lt;!-- Begin .purchase-table --&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="contrast th_status" style="padding:10px;"&gt;&lt;?php gb_e('Status'); ?&gt; &lt;/th&gt; &lt;th class="purchase-purchase_deal_title-title contrast" style="padding:10px;"&gt;&lt;?php gb_e('Deal'); ?&gt;&lt;/th&gt; &lt;th class="contrast th_total_sold" style="padding:10px;"&gt;&lt;?php gb_e('Total Sold'); ?&gt;&lt;/th&gt; &lt;th class="contrast th_published" style="padding:10px;"&gt;&lt;?php gb_e('Published'); ?&gt;&lt;/th&gt; &lt;th class="contrast th_category" style="padding:10px;"&gt; &lt;form action="" method="get" &gt; &lt;?php $selected = ( isset( $_GET['filter'] ) &amp;&amp; $_GET['filter'] != '' ) ? $_GET['filter'] : 0 ; $args = array( 'show_option_none' =&gt; gb__('Category Filter'), 'orderby' =&gt; 'name', 'hide_empty' =&gt; 1, 'exclude' =&gt; '81,82,83,84,85,86,87,88,89,90,91,92', // comma separated list of ids. 'echo' =&gt; 0, 'name' =&gt; 'filter', 'selected' =&gt; $selected, 'taxonomy' =&gt; gb_get_deal_cat_slug() ); $select = wp_dropdown_categories( $args ); $select = preg_replace("#&lt;select([^&gt;]*)&gt;#", "&lt;select$1 onchange='return this.form.submit()'&gt;", $select); echo $select; ?&gt; &lt;noscript&gt;&lt;div&gt;&lt;input type="submit" value="View" /&gt;&lt;/div&gt;&lt;/noscript&gt; &lt;/form&gt; &lt;/th&gt; &lt;th class="contrast th_reports" style="padding:10px;"&gt;&lt;?php gb_e('Reports'); ?&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php while ($deals-&gt;have_posts()) : $deals-&gt;the_post(); // Build an array of the deal's categories. $category_array = array(); $cats = gb_get_deal_categories( get_the_ID() ); foreach ( $cats as $cat ) { $category_array[] = '&lt;a href="'.get_term_link( $cat-&gt;slug, gb_get_deal_cat_slug() ).'"&gt;'.$cat-&gt;name.'&lt;/a&gt;'; } ?&gt; &lt;tr id="published_deal_&lt;?php the_ID() ?&gt;"&gt; &lt;td class="td_status"&gt; &lt;?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'sales_admin' ) ) || ( gb_is_user_merchant_role( array( 'sales_admin' ) ) &amp;&amp; in_array( gb_get_status(), array( 'open', 'closed' ) ) ) ): ?&gt; &lt;span class="alt_button&lt;?php if (gb_get_status() == 'closed') echo ' contrast_button' ?&gt;"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php echo gb_get_status() ?&gt;&lt;/a&gt;&lt;/span&gt; &lt;br/&gt; &lt;?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin', 'sales_admin' ) ) ): ?&gt; &lt;a href="#" class="deal_suspend_button alt_button contrast_button" rel="&lt;?php the_ID() ?&gt;"&gt;&lt;?php gb_e('Suspend') ?&gt;&lt;/a&gt; &lt;?php endif ?&gt; &lt;?php endif ?&gt; &lt;/td&gt; &lt;td class="purchase_deal_title"&gt; &lt;?php the_title() ?&gt; &lt;br/&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" target="_blank"&gt;&lt;?php gb_e('View Deal') ?&gt;&lt;/a&gt; &lt;?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin', 'sales_admin' ) ) ): ?&gt; &lt;a href="&lt;?php gb_deal_edit_url() ?&gt;" target="_blank"&gt;&lt;?php gb_e('Edit') ?&gt;&lt;/a&gt; &lt;?php endif ?&gt; &lt;/td&gt; &lt;td class="td_total_sold"&gt;&lt;?php gb_number_of_purchases() ?&gt;&lt;/td&gt; &lt;td class="td_published"&gt;&lt;p&gt;&lt;?php printf( gb__('Published: %s'), get_the_date() ) ?&gt;&lt;/p&gt;&lt;p&gt;&lt;?php printf( gb__('Modified: %s'), get_the_modified_date() ) ?&gt;&lt;/p&gt;&lt;/td&gt; &lt;td class="td_category"&gt;&lt;?php echo implode( ', ', $category_array ) ?&gt;&lt;/td&gt; &lt;td class="td_reports"&gt; &lt;?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin' ) ) ): ?&gt; &lt;span class="report_button"&gt;&lt;?php gb_merchant_purchase_report_link() ?&gt;&lt;/span&gt; &lt;?php endif ?&gt; &lt;span class="report_button"&gt;&lt;?php gb_merchant_voucher_report_link() ?&gt;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endwhile; ?&gt; &lt;/tbody&gt; &lt;/table&gt;&lt;!-- End .purchase-table --&gt; &lt;?php } else { echo '&lt;p&gt;'.gb__('No sales info.').'&lt;/p&gt;'; } } else { echo '&lt;p&gt;'.gb__('Restricted to Businesses.').'&lt;/p&gt;'; } ?&gt; </code></pre> <p></p> <pre><code>&lt;?php if ( $deals-&gt;max_num_pages &gt; 1 ) : ?&gt; &lt;div id="nav-below" class="navigation clearfix"&gt; &lt;div class="nav-previous"&gt;&lt;?php next_posts_link( gb__( '&lt;span class="meta-nav"&gt;&amp;larr;&lt;/span&gt; Older deals' ), $deals-&gt;max_num_pages ); ?&gt;&lt;/div&gt; &lt;div class="nav-next"&gt;&lt;?php previous_posts_link( gb__( 'Newer deals &lt;span class="meta-nav"&gt;&amp;rarr;&lt;/span&gt;' ), $deals-&gt;max_num_pages ); ?&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- #nav-below --&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code></pre>
[ { "answer_id": 179718, "author": "Jason Murray", "author_id": 68194, "author_profile": "https://wordpress.stackexchange.com/users/68194", "pm_score": -1, "selected": false, "text": "<p>The <code>previous_posts_link</code> and <code>next_posts_link</code> functions are for archive page pagination, they both check if <code>is_single</code> is not true, so will not work on any sort of single post, page, or custom post type.</p>\n\n<p>You need to use <code>paginate_links</code> instead:\n<a href=\"http://codex.wordpress.org/Function_Reference/paginate_links\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/paginate_links</a></p>\n" }, { "answer_id": 179726, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>As already pointed out in comments</p>\n\n<ul>\n<li><p><code>gb_bypass_filter</code> is not a valid parameter for <code>WP_Query</code>. If you want to suppress to effect of filters on your query, add <code>'suppress_filters' =&gt; true</code> to your query arguments</p></li>\n<li><p><code>previous_posts_link()</code> does not accept two arguments, only one. Unlike <code>next_posts_link()</code>, it does not have the second <code>$max_pages</code> parameter. So you can remove that part from your function</p></li>\n<li><p>When using <code>WP_Query</code>, you should use <code>wp_reset_postdata()</code>, not <code>wp_reset_query()</code>. The latter is used with <code>query_posts</code> which you should never ever use.</p></li>\n<li><p>If this is a static frontpage, you should use <code>page</code> as value to your <code>paged</code> parameter, not <code>paged</code></p></li>\n</ul>\n\n<p>I had a second look at your code, and it does seem that your code is a bit disjointed. Make the following adjustments</p>\n\n<ul>\n<li><p>Move your pagination to just below the line <code>endwhile</code> or <code>&lt;/table&gt;</code> , depending where you would want to display your pagination. The latter however looks like the correct place</p></li>\n<li><p>Move <code>wp_reset_postdata()</code> to just below your pagination, this should all be between <code>endwhile</code> and the first occurance of <code>} else {</code>. The reason for this is, when there is no posts, what are you resetting :-)</p></li>\n</ul>\n\n<p>Apart from that, your code should work and paginate as normal. If it does not, try the following</p>\n\n<ul>\n<li><p>Add the <code>suppress_filters</code> argument to your query. This will be a test to see if you don't have external filters that are modifying your query</p></li>\n<li><p>Turn debug on, and check for any obvious bugs and errors</p></li>\n<li><p>Flush your permalinks again by visiting the permalink settings page</p></li>\n<li><p>Dump your custom query (<code>var_dump($deals);</code>) and check thst all inputs and outputs is what you expect them to be. Pay attention to <code>max_num_pages</code> and make sure that you have more than one page</p></li>\n<li><p>Deactivate all plugins one by one to eliminate them as possible causes of your issue. Also, clear all caches. Also try your code on a bundled theme</p></li>\n</ul>\n\n<p>Apart from that, it is really difficult to say what is causing your issue</p>\n" } ]
2015/02/28
[ "https://wordpress.stackexchange.com/questions/179713", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25277/" ]
I spent hours trying to find a solution to this, but I am not able to figure it out. I have a table that shows user's data and I am trying to add pagination to it. I have tried by adding "paged" in the array but when I click on the link I get "Page not found". If I understand correctly the problem is created due to the fact that I have a table generated instead of "calling" posts. Here's what I have now: ``` <?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'deal_admin' ) ) ): ?> <div class="dashboard_container section main_block"> <?php // Purchase history if ( gb_account_merchant_id() ) { $deals = null; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => gb_get_deal_post_type(), 'post__in' => gb_get_merchants_deal_ids(gb_account_merchant_id()), 'post_status' => 'publish', 'gb_bypass_filter' => TRUE, 'posts_per_page' => 5, // return this many 'paged' => $paged, 'tax_query' => array( array( 'taxonomy' => gb_get_deal_cat_slug(), 'field' => 'id', 'terms' => array( 81,82,83,84,85,86,87,88,89,90,91,92 ), 'operator' => 'NOT IN', ), ), ); if ( isset( $_GET['filter'] ) && $_GET['filter'] != '-1' ) { $args['tax_query'][] = array( 'taxonomy' => gb_get_deal_cat_slug(), 'field' => 'id', 'terms' => array( $_GET['filter'] ), ); } $deals = new WP_Query($args); if ($deals->have_posts()) { ?> <?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin' ) ) ): ?> <span class="specialLink_here" style="font-size:16px;"><a href="<?php gb_merchant_purchases_report_url( gb_account_merchant_id() ) ?>" class="report_button"><?php gb_e('Purchase History') ?></a> | </span> <?php if ( function_exists( 'gb_sales_summary_report_url' ) ): ?> <span class="specialLink_here" style="font-size:16px;"><a href="<?php gb_sales_summary_report_url() ?>" class="report_button"><?php gb_e('Sales Summary Report') ?></a> | </span> <?php endif ?> <?php endif ?> <?php if ( !function_exists('gb_is_user_merchant_role') || gb_is_user_merchant_role( array( 'merchant_admin', 'sales_admin' ) ) ): ?> <?php if ( function_exists( 'sec_get_users_report_url' ) ): ?> <span class="specialLink_here" style="font-size:16px;"><a href="<?php echo sec_get_users_report_url() ?>" class="report_button"><?php gb_e('Customer Report') ?></a></span> <?php endif ?> <?php endif ?> <table class="report_table merchant_dashboard" style="margin-top:20px;"><!-- Begin .purchase-table --> <thead> <tr> <th class="contrast th_status" style="padding:10px;"><?php gb_e('Status'); ?> </th> <th class="purchase-purchase_deal_title-title contrast" style="padding:10px;"><?php gb_e('Deal'); ?></th> <th class="contrast th_total_sold" style="padding:10px;"><?php gb_e('Total Sold'); ?></th> <th class="contrast th_published" style="padding:10px;"><?php gb_e('Published'); ?></th> <th class="contrast th_category" style="padding:10px;"> <form action="" method="get" > <?php $selected = ( isset( $_GET['filter'] ) && $_GET['filter'] != '' ) ? $_GET['filter'] : 0 ; $args = array( 'show_option_none' => gb__('Category Filter'), 'orderby' => 'name', 'hide_empty' => 1, 'exclude' => '81,82,83,84,85,86,87,88,89,90,91,92', // comma separated list of ids. 'echo' => 0, 'name' => 'filter', 'selected' => $selected, 'taxonomy' => gb_get_deal_cat_slug() ); $select = wp_dropdown_categories( $args ); $select = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $select); echo $select; ?> <noscript><div><input type="submit" value="View" /></div></noscript> </form> </th> <th class="contrast th_reports" style="padding:10px;"><?php gb_e('Reports'); ?></th> </tr> </thead> <tbody> <?php while ($deals->have_posts()) : $deals->the_post(); // Build an array of the deal's categories. $category_array = array(); $cats = gb_get_deal_categories( get_the_ID() ); foreach ( $cats as $cat ) { $category_array[] = '<a href="'.get_term_link( $cat->slug, gb_get_deal_cat_slug() ).'">'.$cat->name.'</a>'; } ?> <tr id="published_deal_<?php the_ID() ?>"> <td class="td_status"> <?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'sales_admin' ) ) || ( gb_is_user_merchant_role( array( 'sales_admin' ) ) && in_array( gb_get_status(), array( 'open', 'closed' ) ) ) ): ?> <span class="alt_button<?php if (gb_get_status() == 'closed') echo ' contrast_button' ?>"><a href="<?php the_permalink() ?>"><?php echo gb_get_status() ?></a></span> <br/> <?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin', 'sales_admin' ) ) ): ?> <a href="#" class="deal_suspend_button alt_button contrast_button" rel="<?php the_ID() ?>"><?php gb_e('Suspend') ?></a> <?php endif ?> <?php endif ?> </td> <td class="purchase_deal_title"> <?php the_title() ?> <br/> <a href="<?php the_permalink() ?>" target="_blank"><?php gb_e('View Deal') ?></a> <?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin', 'sales_admin' ) ) ): ?> <a href="<?php gb_deal_edit_url() ?>" target="_blank"><?php gb_e('Edit') ?></a> <?php endif ?> </td> <td class="td_total_sold"><?php gb_number_of_purchases() ?></td> <td class="td_published"><p><?php printf( gb__('Published: %s'), get_the_date() ) ?></p><p><?php printf( gb__('Modified: %s'), get_the_modified_date() ) ?></p></td> <td class="td_category"><?php echo implode( ', ', $category_array ) ?></td> <td class="td_reports"> <?php if ( !function_exists('gb_is_user_merchant_role') || !gb_is_user_merchant_role( array( 'coupon_admin' ) ) ): ?> <span class="report_button"><?php gb_merchant_purchase_report_link() ?></span> <?php endif ?> <span class="report_button"><?php gb_merchant_voucher_report_link() ?></span> </td> </tr> <?php endwhile; ?> </tbody> </table><!-- End .purchase-table --> <?php } else { echo '<p>'.gb__('No sales info.').'</p>'; } } else { echo '<p>'.gb__('Restricted to Businesses.').'</p>'; } ?> ``` ``` <?php if ( $deals->max_num_pages > 1 ) : ?> <div id="nav-below" class="navigation clearfix"> <div class="nav-previous"><?php next_posts_link( gb__( '<span class="meta-nav">&larr;</span> Older deals' ), $deals->max_num_pages ); ?></div> <div class="nav-next"><?php previous_posts_link( gb__( 'Newer deals <span class="meta-nav">&rarr;</span>' ), $deals->max_num_pages ); ?></div> </div><!-- #nav-below --> <?php endif; ?> <?php wp_reset_query(); ?> ```
As already pointed out in comments * `gb_bypass_filter` is not a valid parameter for `WP_Query`. If you want to suppress to effect of filters on your query, add `'suppress_filters' => true` to your query arguments * `previous_posts_link()` does not accept two arguments, only one. Unlike `next_posts_link()`, it does not have the second `$max_pages` parameter. So you can remove that part from your function * When using `WP_Query`, you should use `wp_reset_postdata()`, not `wp_reset_query()`. The latter is used with `query_posts` which you should never ever use. * If this is a static frontpage, you should use `page` as value to your `paged` parameter, not `paged` I had a second look at your code, and it does seem that your code is a bit disjointed. Make the following adjustments * Move your pagination to just below the line `endwhile` or `</table>` , depending where you would want to display your pagination. The latter however looks like the correct place * Move `wp_reset_postdata()` to just below your pagination, this should all be between `endwhile` and the first occurance of `} else {`. The reason for this is, when there is no posts, what are you resetting :-) Apart from that, your code should work and paginate as normal. If it does not, try the following * Add the `suppress_filters` argument to your query. This will be a test to see if you don't have external filters that are modifying your query * Turn debug on, and check for any obvious bugs and errors * Flush your permalinks again by visiting the permalink settings page * Dump your custom query (`var_dump($deals);`) and check thst all inputs and outputs is what you expect them to be. Pay attention to `max_num_pages` and make sure that you have more than one page * Deactivate all plugins one by one to eliminate them as possible causes of your issue. Also, clear all caches. Also try your code on a bundled theme Apart from that, it is really difficult to say what is causing your issue
179,752
<p>I have two <code>WP_query</code> loops in my frontpage.php file:</p> <pre><code>&lt;div id="aanbod"&gt; &lt;div class="container-fluid section-name-cont"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 section-name"&gt;&lt;h1&gt;Aanbod&lt;/h1&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $args = array( 'post_type' =&gt; 'vastgoedobject', 'meta_key' =&gt; 'status', 'meta_value' =&gt; array('Te Huur', 'Binnenkort te huur'), 'posts_per_page' =&gt;-1, ); $aanbod_query = new WP_Query( $args ); if ( have_posts() ) : while ( $aanbod_query-&gt;have_posts() ) : $aanbod_query-&gt;the_post(); ?&gt; &lt;div class="content-section-&lt;?php if( $the_query-&gt;current_post%2 == 1 ){ echo 'b';}else{ echo 'a';} ?&gt;"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-5 &lt;?php if( $the_query-&gt;current_post%2 == 1 ){ echo 'col-lg-offset-1 col-sm-push-6 ';} ?&gt;col-sm-6 lead-parent"&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;h2 class="section-heading"&gt;&lt;?php the_field('straat'); ?&gt; &lt;?php the_field('huisnummer'); ?&gt;, &lt;?php the_field('stad'); ?&gt;&lt;/h2&gt;&lt;/a&gt; &lt;span class="label label-default"&gt;&lt;?php the_field('status'); ?&gt;&lt;/span&gt; &lt;span class="label label-default"&gt;&lt;?php echo $euro ;?&gt;&lt;?php the_field('totale_huurprijs'); ?&gt;,-&lt;/span&gt; &lt;span class="label label-default"&gt;&lt;?php the_field('verdieping'); ?&gt;&lt;/span&gt; &lt;span class="label label-default"&gt;&lt;?php the_field('aantal_kamers'); ?&gt;-kamer &lt;?php the_field('beschrijving_vastgoed'); ?&gt;&lt;/span&gt; &lt;span class="label label-default"&gt;&lt;?php the_field('totaaloppervlak'); ?&gt; &lt;?php echo $m2 ;?&gt;&lt;/span&gt; &lt;?php the_field('beschrijving'); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;button type="button" class="btn btn-default"&gt;Bekijk &lt;?php the_field('beschrijving_vastgoed'); ?&gt;&lt;/button&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-lg-5 &lt;?php if( $the_query-&gt;current_post%2 == 1 ){ echo 'col-sm-pull-6';}else{ echo 'col-lg-offset-2';} ?&gt; col-sm-6"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class="foto-wrapper"&gt; &lt;?php if ( !$detect-&gt;isMobile() ) { echo get_image_object_acf('img-responsive img-rounded', 'false', 'foto', '', 'fp-aanbod', 'glyphicon-share-alt'); } else { echo get_image_object_acf('img-responsive img-rounded', 'false', 'foto', '', 'fp-aanbod', ''); } ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; else: ?&gt; &lt;h1&gt;Kampbeheer heeft momenteel niks te huur!&lt;/h1&gt; &lt;?php endif; rewind_posts(); ?&gt; </code></pre> <p></p> <pre><code>&lt;div id="onlangs-verhuurd"&gt; &lt;div class="container-fluid section-name-cont"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 section-name"&gt;&lt;h1&gt;Onlangs Verhuurd&lt;/h1&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $args = array( 'post_type' =&gt; 'vastgoedobject', 'meta_key' =&gt; 'status', 'meta_value' =&gt; array('Verhuurd'), 'posts_per_page' =&gt; 4, ); $verhuurd_query = new WP_Query( $args ); ?&gt; &lt;?php if ( have_posts() ) : while ( $verhuurd_query-&gt;have_posts() ) : $verhuurd_query-&gt;the_post(); ?&gt; &lt;div class="content-section-&lt;?php if( $the_query-&gt;current_post%2 == 0 ){ echo 'b';}else{ echo 'a';} ?&gt;"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-5 &lt;?php if( $the_query-&gt;current_post%2 == 0 ){ echo 'col-lg-offset-1 col-sm-push-6 ';} ?&gt;col-sm-6 lead-parent"&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;h2 class="section-heading"&gt;&lt;?php the_field('straat'); ?&gt;, &lt;?php the_field('stad'); ?&gt;&lt;/h2&gt; &lt;?php if(get_field('totaaloppervlak')) { ?&gt;&lt;span class="label label-default"&gt;&lt;?php the_field('totaaloppervlak'); ?&gt; &lt;?php echo $m2 ;?&gt;&lt;/span&gt;&lt;?php } ?&gt; &lt;?php the_field('beschrijving'); ?&gt; &lt;/div&gt; &lt;div class="col-lg-5 &lt;?php if( $the_query-&gt;current_post%2 == 0 ){ echo 'col-sm-pull-6';}else{ echo 'col-lg-offset-2';} ?&gt; col-sm-6 foto-wrapper"&gt; &lt;?php echo get_image_object_acf('img-responsive img-rounded', 'false', 'foto', '', 'fp-aanbod', '') ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;Niks te weergeven hier!&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre> <p></p> <p>The <code>&lt;?php endwhile; else: ?&gt;</code> part is not working, it is just displaying nothing instead of <code>&lt;h1&gt;Kampbeheer heeft momenteel niks te huur!&lt;/h1&gt;</code> or <code>&lt;p&gt;Niks te weergeven hier!&lt;/p&gt;</code> when no posts are queried</p> <p>What am I missing here?</p>
[ { "answer_id": 179754, "author": "Manny Fleurmond", "author_id": 2234, "author_profile": "https://wordpress.stackexchange.com/users/2234", "pm_score": 1, "selected": false, "text": "<p>The function <code>have_posts</code> is for the main loop, so the <code>if</code> statement is checking the main loop, which will probably always have posts. You want to use the custom query's <code>have_posts</code> for the <code>if</code> statement instead. </p>\n\n<pre><code>if ( $verhuurd_query-&gt;have_posts() ) : while ( $verhuurd_query-&gt;have_posts() ) : $verhuurd_query-&gt;the_post(); ?&gt;\n</code></pre>\n" }, { "answer_id": 179756, "author": "s_ferdie", "author_id": 56398, "author_profile": "https://wordpress.stackexchange.com/users/56398", "pm_score": 3, "selected": true, "text": "<p>Try to change:</p>\n\n<pre><code>&lt;?php if ( have_posts() ) \n</code></pre>\n\n<p>To</p>\n\n<pre><code>&lt;?php if ( $verhuurd_query-&gt;have_posts() )\n</code></pre>\n" } ]
2015/02/28
[ "https://wordpress.stackexchange.com/questions/179752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68349/" ]
I have two `WP_query` loops in my frontpage.php file: ``` <div id="aanbod"> <div class="container-fluid section-name-cont"> <div class="container"> <div class="row"> <div class="col-xs-12 section-name"><h1>Aanbod</h1></div> </div> </div> </div> <?php $args = array( 'post_type' => 'vastgoedobject', 'meta_key' => 'status', 'meta_value' => array('Te Huur', 'Binnenkort te huur'), 'posts_per_page' =>-1, ); $aanbod_query = new WP_Query( $args ); if ( have_posts() ) : while ( $aanbod_query->have_posts() ) : $aanbod_query->the_post(); ?> <div class="content-section-<?php if( $the_query->current_post%2 == 1 ){ echo 'b';}else{ echo 'a';} ?>"> <div class="container"> <div class="row"> <div class="col-lg-5 <?php if( $the_query->current_post%2 == 1 ){ echo 'col-lg-offset-1 col-sm-push-6 ';} ?>col-sm-6 lead-parent"> <div class="clearfix"></div> <a href="<?php the_permalink(); ?>"><h2 class="section-heading"><?php the_field('straat'); ?> <?php the_field('huisnummer'); ?>, <?php the_field('stad'); ?></h2></a> <span class="label label-default"><?php the_field('status'); ?></span> <span class="label label-default"><?php echo $euro ;?><?php the_field('totale_huurprijs'); ?>,-</span> <span class="label label-default"><?php the_field('verdieping'); ?></span> <span class="label label-default"><?php the_field('aantal_kamers'); ?>-kamer <?php the_field('beschrijving_vastgoed'); ?></span> <span class="label label-default"><?php the_field('totaaloppervlak'); ?> <?php echo $m2 ;?></span> <?php the_field('beschrijving'); ?> <a href="<?php the_permalink(); ?>"><button type="button" class="btn btn-default">Bekijk <?php the_field('beschrijving_vastgoed'); ?></button></a> </div> <div class="col-lg-5 <?php if( $the_query->current_post%2 == 1 ){ echo 'col-sm-pull-6';}else{ echo 'col-lg-offset-2';} ?> col-sm-6"> <a href="<?php the_permalink(); ?>" class="foto-wrapper"> <?php if ( !$detect->isMobile() ) { echo get_image_object_acf('img-responsive img-rounded', 'false', 'foto', '', 'fp-aanbod', 'glyphicon-share-alt'); } else { echo get_image_object_acf('img-responsive img-rounded', 'false', 'foto', '', 'fp-aanbod', ''); } ?> </a> </div> </div> </div> </div> <?php endwhile; else: ?> <h1>Kampbeheer heeft momenteel niks te huur!</h1> <?php endif; rewind_posts(); ?> ``` ``` <div id="onlangs-verhuurd"> <div class="container-fluid section-name-cont"> <div class="container"> <div class="row"> <div class="col-xs-12 section-name"><h1>Onlangs Verhuurd</h1></div> </div> </div> </div> <?php $args = array( 'post_type' => 'vastgoedobject', 'meta_key' => 'status', 'meta_value' => array('Verhuurd'), 'posts_per_page' => 4, ); $verhuurd_query = new WP_Query( $args ); ?> <?php if ( have_posts() ) : while ( $verhuurd_query->have_posts() ) : $verhuurd_query->the_post(); ?> <div class="content-section-<?php if( $the_query->current_post%2 == 0 ){ echo 'b';}else{ echo 'a';} ?>"> <div class="container"> <div class="row"> <div class="col-lg-5 <?php if( $the_query->current_post%2 == 0 ){ echo 'col-lg-offset-1 col-sm-push-6 ';} ?>col-sm-6 lead-parent"> <div class="clearfix"></div> <h2 class="section-heading"><?php the_field('straat'); ?>, <?php the_field('stad'); ?></h2> <?php if(get_field('totaaloppervlak')) { ?><span class="label label-default"><?php the_field('totaaloppervlak'); ?> <?php echo $m2 ;?></span><?php } ?> <?php the_field('beschrijving'); ?> </div> <div class="col-lg-5 <?php if( $the_query->current_post%2 == 0 ){ echo 'col-sm-pull-6';}else{ echo 'col-lg-offset-2';} ?> col-sm-6 foto-wrapper"> <?php echo get_image_object_acf('img-responsive img-rounded', 'false', 'foto', '', 'fp-aanbod', '') ?> </div> </div> </div> </div> <?php endwhile; else: ?> <p>Niks te weergeven hier!</p> <?php endif; ?> ``` The `<?php endwhile; else: ?>` part is not working, it is just displaying nothing instead of `<h1>Kampbeheer heeft momenteel niks te huur!</h1>` or `<p>Niks te weergeven hier!</p>` when no posts are queried What am I missing here?
Try to change: ``` <?php if ( have_posts() ) ``` To ``` <?php if ( $verhuurd_query->have_posts() ) ```
179,757
<p>I wrote some extra fields for my custom taxonomy. I added the form fields to the add form. I got it to save by handling the appropriate values in <code>$_POST</code>. In 4.1.x, the add form is Ajax-ified. How can I clear out the form fields on success?</p> <p>More specifically, how can I view the response to the <code>add-tag</code> admin ajax action?</p>
[ { "answer_id": 179760, "author": "Jason Murray", "author_id": 68194, "author_profile": "https://wordpress.stackexchange.com/users/68194", "pm_score": 2, "selected": false, "text": "<p>You could achieve this with a little bit of jQuery:</p>\n\n<p>Create this file within THEMEFOLDER/js/ called field-clear.js and replace <code>#formID</code> with the ID of the form you would like to reset:</p>\n\n<pre><code>//Code runs when an ajax request succeeds\njQuery( document ).ajaxSuccess(function( event, xhr, settings ) {\n //Check ajax action of request that succeeded\n if(settings.action == 'add_tag') {\n //Reset the form\n jQuery('#formID')[0].reset();\n\n //Send ajax response to console.\n console.log(\"Triggered ajaxSuccess handler. The ajax response was: \" + xhr.responseText );\n }\n});\n</code></pre>\n\n<p>Then in functions.php load your javascript:</p>\n\n<pre><code>wp_register_script('field-clear-script', get_stylesheet_directory_uri() . '/js/field-clear.js', array('jquery'), null, true);\n\nfunction field_clear_load_scripts() {\n wp_enqueue_script('field-clear-script');\n}\nadd_action('admin_enqueue_scripts', 'field_clear_load_scripts');\n</code></pre>\n\n<p>EDIT - Added code to display ajax response text. Added check for ajax action parameter. Changed enqueue function to enqueue on admin as I think this is where it's required.</p>\n" }, { "answer_id": 312533, "author": "Walf", "author_id": 27856, "author_profile": "https://wordpress.stackexchange.com/users/27856", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/a/179760/27856\">Jason's answer</a> is very close, which led to this solution for me on WP 4.9:</p>\n\n<pre><code>$(document).ajaxSuccess(function(evt, xhr, opts) {\n if (\n xhr.status &gt;= 200\n &amp;&amp; xhr.status &lt; 300\n &amp;&amp; opts.data\n &amp;&amp; /(^|&amp;)action=add-tag($|&amp;)/.test(opts.data)\n &amp;&amp; /(^|&amp;)taxonomy=YOUR_TAXONOMY($|&amp;)/.test(opts.data)\n &amp;&amp; xhr.responseXML\n &amp;&amp; $('wp_error', xhr.responseXML).length == 0\n ) {\n // clear your fields\n }\n});\n</code></pre>\n" } ]
2015/02/28
[ "https://wordpress.stackexchange.com/questions/179757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36036/" ]
I wrote some extra fields for my custom taxonomy. I added the form fields to the add form. I got it to save by handling the appropriate values in `$_POST`. In 4.1.x, the add form is Ajax-ified. How can I clear out the form fields on success? More specifically, how can I view the response to the `add-tag` admin ajax action?
You could achieve this with a little bit of jQuery: Create this file within THEMEFOLDER/js/ called field-clear.js and replace `#formID` with the ID of the form you would like to reset: ``` //Code runs when an ajax request succeeds jQuery( document ).ajaxSuccess(function( event, xhr, settings ) { //Check ajax action of request that succeeded if(settings.action == 'add_tag') { //Reset the form jQuery('#formID')[0].reset(); //Send ajax response to console. console.log("Triggered ajaxSuccess handler. The ajax response was: " + xhr.responseText ); } }); ``` Then in functions.php load your javascript: ``` wp_register_script('field-clear-script', get_stylesheet_directory_uri() . '/js/field-clear.js', array('jquery'), null, true); function field_clear_load_scripts() { wp_enqueue_script('field-clear-script'); } add_action('admin_enqueue_scripts', 'field_clear_load_scripts'); ``` EDIT - Added code to display ajax response text. Added check for ajax action parameter. Changed enqueue function to enqueue on admin as I think this is where it's required.
179,832
<p>Here is my current code,</p> <p><em>aio_menu.php</em></p> <pre><code>&lt;?php defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); add_action( 'admin_menu', 'AIO_menu_creator' ); function AIO_menu_creator() { add_menu_page( 'AIO WooCommerce Plugin', 'AIO', 'manage_options', 'aio-dashboard', plugins_url('AIO-WooCommerce-Plugin/menu/aio_dashboard.php'), plugins_url('AIO-WooCommerce-Plugin/ico.png') , '81.912514514511451' ); } require_once 'aio_dashboard.php'; ?&gt; </code></pre> <p><em>aio_dashboard.php</em></p> <pre><code>&lt;?php function my_plugin_options() { if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); } echo '&lt;div class="wrap"&gt;'; echo '&lt;p&gt;Here is where the form would go if I actually had options.&lt;/p&gt;'; echo '&lt;/div&gt;'; } add_action( 'current_screen', 'my_plugin_options' ); ?&gt; </code></pre> <p><img src="https://i.stack.imgur.com/tEkx2.png" alt="the image of the page"></p> <p>in my main plugin file,</p> <p><code>require_once 'menu/aio_menu.php';</code></p> <p>I want to add sub menu items like, dashboard, shipping editor, price specifier and etc.</p> <p>So, aio_menu will have all my menu's specified and I will have aio_dashboard and so on for the page content.</p> <p>Now I want to align the content I get in the middle of the page and make sure the notifications which are shown are properly shown. I know I am doing something wrong in aio_dashboard file.</p> <p>Can anyone just suggest me how to get the content I want in the page correctly?Just this,</p> <blockquote> <p>a h3 title DASHBOARD</p> </blockquote> <p>and below it </p> <blockquote> <p>'content goes here'</p> </blockquote> <p>It should be in the admin page.</p> <p>Here is an example of where I want my content, <img src="https://i.stack.imgur.com/3B56N.png" alt="enter image description here"></p> <p>I have edited it with inspect element. You can compare the first image and second so any ideas how to get it in the correct place ?</p>
[ { "answer_id": 179850, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>The <code>$function</code> argument of <code>add_menu_page</code> should be a function that produces your page output, or if omitted, then the <code>$menu_slug</code> argument can be a file that when included will output the menu page.</p>\n\n<p>But your output right now has nothing to do with the <code>add_menu_page</code> call, the problem is that you're requiring <code>aio_dashboard.php</code>, which has a function hooked to <code>current_screen</code>. The <code>current_screen</code> action should not generate output, that's not what it's for, it fires too early in the load process. Its purpose is for adding filters and actions based on the current admin page being viewed.</p>\n\n<p>Change the <code>add_menu_page</code> <code>$function</code> argument to contain the function that outputs the page content, remove the <code>add_action</code> call hooking that function to <code>current_screen</code>.</p>\n" }, { "answer_id": 179880, "author": "kks21199", "author_id": 68381, "author_profile": "https://wordpress.stackexchange.com/users/68381", "pm_score": 0, "selected": false, "text": "<p>For anyone who wants to add their own admin menu ;) The format is, </p>\n\n<p><code>&lt;?php\nadd_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );\n?&gt;</code></p>\n\n<p><code>&lt;?php add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function ); ?&gt;</code></p>\n\n<p>(from wordpress codex)</p>\n\n<pre><code>&lt;?php\n defined( 'ABSPATH' ) or die( 'No script kiddies please!' );\n add_action( 'admin_menu', 'mgg_aio_menu_creator' );\n function mgg_aio_menu_creator() {\n\n add_menu_page( 'AIO WooCommerce Plugin', 'AIO', 'manage_options', 'aio-dashboard', 'mgg_aio_dashboard', plugins_url('AIO-WooCommerce-Plugin/ico.png') , '81.912514514511451' ); \n add_submenu_page( 'aio-dashboard', 'AIO WooCommerce Plugin', 'Dashboard', 'manage_options', 'aio-dashboard', 'mgg_aio_dashboard');\n add_submenu_page( 'aio-dashboard', 'Shipping Options | AIO WooCommerce Plugin', 'Shipping Options', 'manage_options', 'aio-shipping-options', 'mgg_aio_shipping_options');\n }\n require_once 'aio_dashboard.php';\n require_once 'aio_shipping_options.php';\n ?&gt;\n</code></pre>\n\n<p>You will have a menu like this,\n<img src=\"https://i.stack.imgur.com/33hbZ.png\" alt=\"enter image description here\"></p>\n" } ]
2015/03/01
[ "https://wordpress.stackexchange.com/questions/179832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68381/" ]
Here is my current code, *aio\_menu.php* ``` <?php defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); add_action( 'admin_menu', 'AIO_menu_creator' ); function AIO_menu_creator() { add_menu_page( 'AIO WooCommerce Plugin', 'AIO', 'manage_options', 'aio-dashboard', plugins_url('AIO-WooCommerce-Plugin/menu/aio_dashboard.php'), plugins_url('AIO-WooCommerce-Plugin/ico.png') , '81.912514514511451' ); } require_once 'aio_dashboard.php'; ?> ``` *aio\_dashboard.php* ``` <?php function my_plugin_options() { if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); } echo '<div class="wrap">'; echo '<p>Here is where the form would go if I actually had options.</p>'; echo '</div>'; } add_action( 'current_screen', 'my_plugin_options' ); ?> ``` ![the image of the page](https://i.stack.imgur.com/tEkx2.png) in my main plugin file, `require_once 'menu/aio_menu.php';` I want to add sub menu items like, dashboard, shipping editor, price specifier and etc. So, aio\_menu will have all my menu's specified and I will have aio\_dashboard and so on for the page content. Now I want to align the content I get in the middle of the page and make sure the notifications which are shown are properly shown. I know I am doing something wrong in aio\_dashboard file. Can anyone just suggest me how to get the content I want in the page correctly?Just this, > > a h3 title DASHBOARD > > > and below it > > 'content goes here' > > > It should be in the admin page. Here is an example of where I want my content, ![enter image description here](https://i.stack.imgur.com/3B56N.png) I have edited it with inspect element. You can compare the first image and second so any ideas how to get it in the correct place ?
The `$function` argument of `add_menu_page` should be a function that produces your page output, or if omitted, then the `$menu_slug` argument can be a file that when included will output the menu page. But your output right now has nothing to do with the `add_menu_page` call, the problem is that you're requiring `aio_dashboard.php`, which has a function hooked to `current_screen`. The `current_screen` action should not generate output, that's not what it's for, it fires too early in the load process. Its purpose is for adding filters and actions based on the current admin page being viewed. Change the `add_menu_page` `$function` argument to contain the function that outputs the page content, remove the `add_action` call hooking that function to `current_screen`.
179,835
<p>I have wordpress site hosted on openshift say example.com. I am redirecting example.com to www.example.com (non www to www). I have created alias for www and non www version and updated my cname with app name.</p> <p>I tried pointing non www cname record to www version and it was working except for homepage (same 301 redirect loop) so i reverted non www cname back to app url.</p> <p>Now www version is serving but non www version is creating 301 redirect loop by redirecting to itself. My wordpress site url is www.example.com and i have not added any htaccess directives.</p> <p>How can i properly redirect non www to www version.</p>
[ { "answer_id": 179837, "author": "George Grigorita", "author_id": 13214, "author_profile": "https://wordpress.stackexchange.com/users/13214", "pm_score": 0, "selected": false, "text": "<p>In your htaccess add the following (before the WordPress rewrites):</p>\n\n<pre><code>Options +FollowSymLinks\nRewriteEngine on\nRewriteCond %{HTTP_HOST} ^example\\.com\nRewriteRule ^(.*)$ http://www.example.com/$1 [R=permanent,L] \n</code></pre>\n\n<p>The above will make a permanent redirect from non-WWW to WWW. </p>\n\n<p>Alternatively you can do this in <a href=\"https://support.google.com/webmasters/answer/44231?hl=en\" rel=\"nofollow\">Google Webmaster Tools</a>. Also, make sure that you have the correct settings in your WP-Admin -> Settings -> General -> Site URL &amp; WordPress URL. </p>\n" }, { "answer_id": 181945, "author": "Harikesh", "author_id": 68383, "author_profile": "https://wordpress.stackexchange.com/users/68383", "pm_score": 3, "selected": true, "text": "<p>I think there is some issue with openshift's php hosting.\nI found <a href=\"https://stackoverflow.com/questions/27773105/openshift-htaccess-rewriterule-doesnt-work\">this thread on stackoverflow</a>.\nSo catch is you append port no after host. \nThis .htaccess code <strong>should work</strong>.</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^example.com$\nRewriteRule (.*) http://www.example.com:80/$1 [R=301,L] \n</code></pre>\n" } ]
2015/03/01
[ "https://wordpress.stackexchange.com/questions/179835", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68383/" ]
I have wordpress site hosted on openshift say example.com. I am redirecting example.com to www.example.com (non www to www). I have created alias for www and non www version and updated my cname with app name. I tried pointing non www cname record to www version and it was working except for homepage (same 301 redirect loop) so i reverted non www cname back to app url. Now www version is serving but non www version is creating 301 redirect loop by redirecting to itself. My wordpress site url is www.example.com and i have not added any htaccess directives. How can i properly redirect non www to www version.
I think there is some issue with openshift's php hosting. I found [this thread on stackoverflow](https://stackoverflow.com/questions/27773105/openshift-htaccess-rewriterule-doesnt-work). So catch is you append port no after host. This .htaccess code **should work**. ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com$ RewriteRule (.*) http://www.example.com:80/$1 [R=301,L] ```
179,840
<p>I've built a child theme of <a href="http://www.elegantthemes.com/gallery/divi/" rel="nofollow noreferrer">Divi Theme</a> to use with <a href="https://buddypress.org/" rel="nofollow noreferrer">Buddypress</a>. So far so good, except for a script conflict on commenting buttons.</p> <p>The theme load a javascript (<code>js/custom.js</code> at 2642:2662) with the following function:</p> <pre><code> $( 'a[href*=#]:not([href=#])' ).click( function() { if ( $(this).closest( '.woocommerce-tabs' ).length &amp;&amp; $(this).closest( '.tabs' ).length ) { return false; } if ( location.pathname.replace( /^\//,'' ) == this.pathname.replace( /^\//,'' ) &amp;&amp; location.hostname == this.hostname ) { var target = $( this.hash ); target = target.length ? target : $( '[name=' + this.hash.slice(1) +']' ); if ( target.length ) { et_pb_smooth_scroll( target, false, 800 ); if ( ! $( '#main-header' ).hasClass( 'et-fixed-header' ) &amp;&amp; $( 'body' ).hasClass( 'et_fixed_nav' ) &amp;&amp; $( window ).width() &gt; 980 ) { setTimeout(function(){ et_pb_smooth_scroll( target, false, 200); }, 500 ); } return false; } } }); </code></pre> <p>This event target the same button that Buddypress use for commenting, preventing AJAX form from loading on click.</p> <p><img src="https://i.stack.imgur.com/u9o0m.png" alt="enter image description here"></p> <p>I don't want to edit the parent theme (custom.js). How can I prevent this conflict? Is there a workaround, maybe from <strong>functions.php</strong>?</p> <p><strong>UPDATE</strong></p> <p>Using <a href="http://codex.wordpress.org/Function_Reference/wp_dequeue_script" rel="nofollow noreferrer">wp_dequeue_script</a> to load that script later, didn't work. When using this code in functions.php</p> <pre><code>function de_script() { wp_dequeue_script( 'divi-custom-script' ); } add_action( 'wp_print_scripts', 'de_script', 100 ); </code></pre> <p>then the full script (custom.js) was not loaded at all.</p>
[ { "answer_id": 179852, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 0, "selected": false, "text": "<p>From a purely WordPress perspective, the only solution I see would be to copy the script to your child theme and make edits to it to remove the conflict. If the parent theme uses <code>get_template_directory_uri</code> to reference the path to the script, you'll also have to dequeue the original, and enqueue your modified version. If the script is loaded using <code>get_stylesheet_directory_uri</code>, then simply mirroring the same hierarchy in your child theme will correctly override the script without having to do anything else.</p>\n\n<p>Of course, the issue will be with parent theme updates adding or modifying that script file, you will have to monitor each update to insure your updated theme is not broken or missing functionality.</p>\n" }, { "answer_id": 179853, "author": "Jason Murray", "author_id": 68194, "author_profile": "https://wordpress.stackexchange.com/users/68194", "pm_score": 0, "selected": false, "text": "<p>I might be off track here, but would removing the <code>return false;</code> from the javascript you posted help?</p>\n\n<p><code>return false;</code> in a click function is like saying:</p>\n\n<pre><code> event.preventDefault();\n event.stopPropagation();\n</code></pre>\n\n<p>I think this is why your other function is not firing as there is no restriction to having multiple handlers bound to the same event on an element. However removing the <code>return false;</code> may cause you other issues.</p>\n" }, { "answer_id": 179906, "author": "Giulio Bonanome", "author_id": 68388, "author_profile": "https://wordpress.stackexchange.com/users/68388", "pm_score": 2, "selected": true, "text": "<p>First of all, to resolve the javascript conflict I've set up a simple <code>tl_custom.js</code> under my theme <code>js/</code> folder, with the following code</p>\n\n<pre><code>jQuery(document).ready(function($) {\n // Remove handler set by themes/Divi/js/custom.js at line 2642\n $( 'a[href*=#]:not([href=#])' ).off();\n});\n</code></pre>\n\n<p>Then I add the script with the following code in <code>functions.php</code></p>\n\n<pre><code>function tl_custom_scripts() {\n if ( ! is_admin() ) {\n $scriptsrc = get_stylesheet_directory_uri() . '/js/';\n wp_register_script( 'tl_custom', $scriptsrc . 'tl_custom.js', '', '', true );\n wp_enqueue_script( 'tl_custom' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'tl_custom_scripts', 20 );\n</code></pre>\n\n<p>The main problem is that the parent theme register <code>custom.js</code> in the footer, so I had to set the <a href=\"http://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow\">wp_register_script</a> last parameter to <code>true</code> and then set <a href=\"http://codex.wordpress.org/Function_Reference/add_action\" rel=\"nofollow\">add_action</a> priority to 20.</p>\n" }, { "answer_id": 212750, "author": "fryvisuals", "author_id": 58187, "author_profile": "https://wordpress.stackexchange.com/users/58187", "pm_score": 1, "selected": false, "text": "<p>I just ran into this same problem with my premium theme not having buddypress support. Disabling the click event removes the ability to have scrollto page anchors which I have on one of my interior pages. So I just target the buddypress class to enable the comment/reply buttons. </p>\n\n<pre><code>if ( $('body').hasClass('buddypress') ) {\n\n $( 'a[href*=#]:not([href=#])' ).off();\n\n}\n</code></pre>\n\n<p>I placed the code in a custom.js file in my child theme then enqueued the resource from functions.php. Make sure the file is enqueued after the premium theme's js.</p>\n" } ]
2015/03/01
[ "https://wordpress.stackexchange.com/questions/179840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68388/" ]
I've built a child theme of [Divi Theme](http://www.elegantthemes.com/gallery/divi/) to use with [Buddypress](https://buddypress.org/). So far so good, except for a script conflict on commenting buttons. The theme load a javascript (`js/custom.js` at 2642:2662) with the following function: ``` $( 'a[href*=#]:not([href=#])' ).click( function() { if ( $(this).closest( '.woocommerce-tabs' ).length && $(this).closest( '.tabs' ).length ) { return false; } if ( location.pathname.replace( /^\//,'' ) == this.pathname.replace( /^\//,'' ) && location.hostname == this.hostname ) { var target = $( this.hash ); target = target.length ? target : $( '[name=' + this.hash.slice(1) +']' ); if ( target.length ) { et_pb_smooth_scroll( target, false, 800 ); if ( ! $( '#main-header' ).hasClass( 'et-fixed-header' ) && $( 'body' ).hasClass( 'et_fixed_nav' ) && $( window ).width() > 980 ) { setTimeout(function(){ et_pb_smooth_scroll( target, false, 200); }, 500 ); } return false; } } }); ``` This event target the same button that Buddypress use for commenting, preventing AJAX form from loading on click. ![enter image description here](https://i.stack.imgur.com/u9o0m.png) I don't want to edit the parent theme (custom.js). How can I prevent this conflict? Is there a workaround, maybe from **functions.php**? **UPDATE** Using [wp\_dequeue\_script](http://codex.wordpress.org/Function_Reference/wp_dequeue_script) to load that script later, didn't work. When using this code in functions.php ``` function de_script() { wp_dequeue_script( 'divi-custom-script' ); } add_action( 'wp_print_scripts', 'de_script', 100 ); ``` then the full script (custom.js) was not loaded at all.
First of all, to resolve the javascript conflict I've set up a simple `tl_custom.js` under my theme `js/` folder, with the following code ``` jQuery(document).ready(function($) { // Remove handler set by themes/Divi/js/custom.js at line 2642 $( 'a[href*=#]:not([href=#])' ).off(); }); ``` Then I add the script with the following code in `functions.php` ``` function tl_custom_scripts() { if ( ! is_admin() ) { $scriptsrc = get_stylesheet_directory_uri() . '/js/'; wp_register_script( 'tl_custom', $scriptsrc . 'tl_custom.js', '', '', true ); wp_enqueue_script( 'tl_custom' ); } } add_action( 'wp_enqueue_scripts', 'tl_custom_scripts', 20 ); ``` The main problem is that the parent theme register `custom.js` in the footer, so I had to set the [wp\_register\_script](http://codex.wordpress.org/Function_Reference/wp_register_script) last parameter to `true` and then set [add\_action](http://codex.wordpress.org/Function_Reference/add_action) priority to 20.
179,856
<p>I've searched high and low and can't seem to get it. </p> <p>I'm trying to output an XML feed with all the images attached to a post from a custom post type:</p> <pre><code>&lt;/BasicDetails&gt; &lt;Pictures&gt; &lt;Picture&gt; &lt;PictureUrl&gt;&lt;?php echo wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID)); ?&gt;&lt;/PictureUrl&gt; &lt;Caption&gt;&lt;/Caption&gt; &lt;/Picture&gt;&lt;Picture&gt; &lt;PictureUrl&gt;&lt;/PictureUrl&gt; &lt;Caption&gt;&lt;/Caption&gt; &lt;/Picture&gt; &lt;/Pictures&gt; </code></pre> <p>I'm using wp_get_attachment_url but it's only returning one image (There's more than one per post)</p> <pre><code> &lt;?php echo wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID)); ?&gt; </code></pre> <p>The <code>&lt;Picture&gt;</code> is a repeating element so it should start an new tree when there's another image attached. </p> <p>Any help would be Amazing!</p>
[ { "answer_id": 179859, "author": "Jason Murray", "author_id": 68194, "author_profile": "https://wordpress.stackexchange.com/users/68194", "pm_score": 3, "selected": true, "text": "<p>You need to loop through the attachments within your post loop, replace the section of code you posted with this (put this together from <a href=\"https://wordpress.org/support/topic/list-all-images-attached-to-a-post-based-on-gallery\" rel=\"nofollow\">some other code I found</a> related to a similar problem, but couldn't test it):</p>\n\n<pre><code>&lt;/BasicDetails&gt;\n&lt;?php $args = array(\n 'post_parent' =&gt; $post-&gt;ID,\n 'post_type' =&gt; 'attachment',\n 'numberposts' =&gt; -1, // show all\n 'post_status' =&gt; 'any',\n 'post_mime_type' =&gt; 'image',\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC'\n );\n\n$images = get_posts($args);\nif($images) { ?&gt;\n&lt;Pictures&gt;\n &lt;?php foreach($images as $image) { ?&gt;\n &lt;Picture&gt;\n &lt;PictureUrl&gt;&lt;?php echo wp_get_attachment_url($image-&gt;ID); ?&gt;&lt;/PictureUrl&gt;\n &lt;Caption&gt;&lt;?php echo $image-&gt;post_excerpt; ?&gt;&lt;/Caption&gt;\n &lt;/Picture&gt;\n &lt;?php } ?&gt;\n&lt;/Pictures&gt;\n&lt;?php } ?&gt;\n&lt;Agent&gt;\n</code></pre>\n\n<p>EDIT - Updated based on asker edits.</p>\n" }, { "answer_id": 351568, "author": "yawar", "author_id": 177622, "author_profile": "https://wordpress.stackexchange.com/users/177622", "pm_score": 2, "selected": false, "text": "<p>use this code in the post loop.</p>\n\n<pre><code>$attimages = get_attached_media('image', $post-&gt;ID);\nforeach ($attimages as $image) {\n echo wp_get_attachment_url($image-&gt;ID).'&lt;br&gt;';\n}\n</code></pre>\n\n<p>this code will return all attached images url</p>\n" } ]
2015/03/01
[ "https://wordpress.stackexchange.com/questions/179856", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4640/" ]
I've searched high and low and can't seem to get it. I'm trying to output an XML feed with all the images attached to a post from a custom post type: ``` </BasicDetails> <Pictures> <Picture> <PictureUrl><?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID)); ?></PictureUrl> <Caption></Caption> </Picture><Picture> <PictureUrl></PictureUrl> <Caption></Caption> </Picture> </Pictures> ``` I'm using wp\_get\_attachment\_url but it's only returning one image (There's more than one per post) ``` <?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID)); ?> ``` The `<Picture>` is a repeating element so it should start an new tree when there's another image attached. Any help would be Amazing!
You need to loop through the attachments within your post loop, replace the section of code you posted with this (put this together from [some other code I found](https://wordpress.org/support/topic/list-all-images-attached-to-a-post-based-on-gallery) related to a similar problem, but couldn't test it): ``` </BasicDetails> <?php $args = array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'numberposts' => -1, // show all 'post_status' => 'any', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC' ); $images = get_posts($args); if($images) { ?> <Pictures> <?php foreach($images as $image) { ?> <Picture> <PictureUrl><?php echo wp_get_attachment_url($image->ID); ?></PictureUrl> <Caption><?php echo $image->post_excerpt; ?></Caption> </Picture> <?php } ?> </Pictures> <?php } ?> <Agent> ``` EDIT - Updated based on asker edits.
179,858
<p>I've googled extensively and tried my best, but I just can't get the first level children of the custom taxonomy in the code below to work! It only displays the parent level. What I am trying to achieve is the following:</p> <pre><code>Level 1 &lt;--- at the moment, it only displays this level Level 2 &lt;-- I want to display this level too Level 3 &lt;-- but NOT this level </code></pre> <p>This is my code so far:</p> <pre><code>function my_dropdown_categories( $taxonomy, $current_selected = '', $include = null ) { // Get all terms of the chosen taxonomy $terms = get_terms($taxonomy, array('orderby' =&gt; 'name')); // our content variable $list_of_terms = '&lt;select id="location" class="selectboxSingle" name="location"&gt;'; if ( ! is_wp_error( $terms ) ) foreach($terms as $term){ // If include array set, exclude unless in array. if ( is_array( $include ) &amp;&amp; ! in_array( $term-&gt;slug, $include ) ) continue; $select = ($current_selected == $term-&gt;slug) ? "selected" : ""; // Note: == if ($term-&gt;parent == 0 ) { // get children of current parent. // $tchildren = get_term_children($term-&gt;term_id, $taxonomy); &lt;- gets ALL children $uchildren =get_terms( $taxonomy, array('hide_empty' =&gt; 0, 'parent' =&gt; $term-&gt;term_id )); $children = array(); foreach ($uchildren as $child) { $cterm = get_term_by( 'id', $child, $taxonomy ); // If include array set, exclude unless in array. if ( is_array( $include ) &amp;&amp; ! in_array( $cterm-&gt;slug, $include ) ) continue; $children[$cterm-&gt;name] = $cterm; } ksort($children); // PARENT TERM if ($term-&gt;count &gt; 0) { $list_of_terms .= '&lt;option class ="group-result" value="'.$term-&gt;slug.'" '.$select.'&gt;' . $term-&gt;name .' &lt;/option&gt;'; } else { $list_of_terms .= '&lt;option value="'.$term-&gt;slug.'" '.$select.'&gt;'. $term-&gt;name .' &lt;/option&gt;'; }; // now the CHILDREN. foreach($children as $child) { $select = ($current_selected == $child-&gt;slug) ? "selected" : ""; // Note: child, not cterm $list_of_terms .= '&lt;option class="result-sub" value="'.$child-&gt;slug.'" '.$select.'&gt;'. $child-&gt;name.' &lt;/option&gt;'; } //end foreach } } $list_of_terms .= '&lt;/select&gt;'; return $list_of_terms; } </code></pre> <p>If someone can help me with this beast, you'll be my freaken hero!</p> <p><strong>EDIT</strong> (more info based on Pieter's answer):</p> <p><em>This is what is being output (all parents):</em></p> <p>Parent 1</p> <p>--Parent 1</p> <p>--Parent 2</p> <p>--Parent 3</p> <p>--Parent 4</p> <p>Parent 2</p> <p>--Parent 2</p> <p>--Parent 1</p> <p>--Parent 3</p> <p>etc</p>
[ { "answer_id": 179905, "author": "Saurabh Shukla", "author_id": 20375, "author_profile": "https://wordpress.stackexchange.com/users/20375", "pm_score": 0, "selected": false, "text": "<p>Check this code</p>\n\n<pre><code>$uchildren =get_terms( 'category', array('hide_empty' =&gt; false, 'parent' =&gt; $term-&gt;term_id ));\n\n$children = array();\nforeach ($uchildren as $child) {\n $cterm = get_term_by( 'id', $child, $taxonomy );\n // If include array set, exclude unless in array.\n if ( is_array( $include ) &amp;&amp; ! in_array( $cterm-&gt;slug, $include ) ) continue;\n $children[$cterm-&gt;name] = $cterm;\n}\n</code></pre>\n\n<p>This line</p>\n\n<pre><code>$cterm = get_term_by( 'id', $child, $taxonomy ); \n</code></pre>\n\n<p>assumes that $child will be an id (and an integer), whereas:</p>\n\n<pre><code>foreach ($uchildren as $child) {\n</code></pre>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/get_terms#Return_Values\" rel=\"nofollow\">gives us an object</a></p>\n\n<p>This also is the reason why this doesn't work as you want:</p>\n\n<pre><code>if ( is_array( $include ) &amp;&amp; ! in_array( $cterm-&gt;slug, $include ) ) continue;\n</code></pre>\n\n<p><strong>From here is junk that I had posted but good sense prevailed, till...</strong></p>\n\n<p>Let's do the fun part:</p>\n\n<pre><code>var_dump($term):\n</code></pre>\n\n<p>Notice the type of each property:</p>\n\n<pre><code>object(stdClass)(9) {\n ...\n [\"parent\"]=&gt;\n string(1) \"0\"\n ...\n}\n</code></pre>\n\n<p>See the <code>parent</code>. It's a string. I know, logically it should be an integer, but it's a string. It sucks, right!</p>\n\n<p>So, your <code>if ($term-&gt;parent == 0 ) {</code> condition is not getting satisfied. Try this instead:</p>\n\n<pre><code>if ( empty( $term-&gt;parent ) ) {\n</code></pre>\n\n<p><strong>here</strong></p>\n" }, { "answer_id": 179909, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>You have two issues here, one is a performance issue, the other is big issue that should return a pile of errors if you enable debug</p>\n\n<p>The performance issue here is your first instance where you are getting the terms. It seems that your goal here is to get only top level terms, yet you get all. I would just add <code>'parent' =&gt; 0</code> to the arguments to get only top level terms. You can then drop the condition where you check <code>if ( $term-&gt;parent == 0 )</code> because all terms will be top level terms which will all have <code>0</code> as term parent, so this condition will always return true</p>\n\n<p>Your big issue is with this code, and I don't understand your logic here</p>\n\n<pre><code> $uchildren =get_terms( $taxonomy, array('hide_empty' =&gt; 0, 'parent' =&gt; $term-&gt;term_id ));\n\n $children = array();\n foreach ($uchildren as $child) {\n $cterm = get_term_by( 'id', $child, $taxonomy );\n // If include array set, exclude unless in array.\n if ( is_array( $include ) &amp;&amp; ! in_array( $cterm-&gt;slug, $include ) ) continue;\n $children[$cterm-&gt;name] = $cterm;\n }\n ksort($children);\n</code></pre>\n\n<p>You are correct in getting your direct term children, so your declaration of <code>$uchildren</code> is fine. From there everything goes haywire</p>\n\n<ul>\n<li><p>Why are you using <a href=\"http://codex.wordpress.org/Function_Reference/get_term_by\" rel=\"noreferrer\"><code>get_term_by()</code></a> here. <code>$child</code> already holds the term properties as you have used <code>get_terms()</code> to retrieve the terms.</p></li>\n<li><p>You are not just using <code>get_term_by()</code> wrongly here, but your arguments are invalid, and you are passing a complete object to it as well. You should consult the codex for proper use of this function. All in all, that section should be removed from your code</p></li>\n</ul>\n\n<p>That section should look something like this</p>\n\n<pre><code> $uchildren =get_terms( $taxonomy, array('hide_empty' =&gt; 0, 'parent' =&gt; $term-&gt;term_id ));\n\n $children = array();\n foreach ($uchildren as $child) {\n if ( is_array( $include ) &amp;&amp; ! in_array( $child-&gt;slug, $include ) ) continue;\n $children[$child-&gt;name] = $child;\n }\n ksort($children);\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Here is a full working code with a couple of bugs fixed. Please see my comments in code for the updates</p>\n\n<pre><code>function my_dropdown_categories( $taxonomy, $current_selected = '', $include = null ) \n{\n /*\n * Declare your variable first. Without this, your code has a bug if no terms are found\n */\n $list_of_terms = '';\n\n /**\n * Get all parent terms. Note we use 'parent' =&gt; 0 to only get top level terms\n *\n * @see get_terms\n * @link http://codex.wordpress.org/Function_Reference/get_terms\n */\n $terms = get_terms( $taxonomy, array( 'orderby' =&gt; 'name', 'parent' =&gt; 0 ) );\n\n /*\n * Use curlies here to enclose your statement. Also, check whether or not you have terms\n */\n if ( $terms &amp;&amp; ! is_wp_error( $terms ) ) {\n\n /*\n * Moved this section inside your if statement. We don't want to display anything on empty terms\n */\n $list_of_terms .= '&lt;select id=\"location\" class=\"selectboxSingle\" name=\"location\"&gt;';\n\n foreach ( $terms as $term ) {\n\n // If include array set, exclude unless in array.\n if ( is_array( $include ) &amp;&amp; ! in_array( $term-&gt;slug, $include ) ) continue;\n\n $select = ($current_selected == $term-&gt;slug) ? \"selected\" : \"\"; // Note: ==\n\n /*\n * Use the parent term term id as parent to get direct children of the term\n * Use child_of if you need to get all descendants of a term\n */\n $uchildren = get_terms( $taxonomy, array('hide_empty' =&gt; 0, 'parent' =&gt; $term-&gt;term_id ));\n\n $children = array();\n foreach ($uchildren as $child) {\n // If include array set, exclude unless in array.\n if ( is_array( $include ) &amp;&amp; ! in_array( $child-&gt;slug, $include ) ) continue;\n $children[$child-&gt;name] = $child;\n }\n ksort($children);\n\n // PARENT TERM \n if ($term-&gt;count &gt; 0) {\n $list_of_terms .= '&lt;option class =\"group-result\" value=\"'.$term-&gt;slug.'\" '.$select.'&gt;' . $term-&gt;name .' &lt;/option&gt;';\n } else {\n $list_of_terms .= '&lt;option value=\"'.$term-&gt;slug.'\" '.$select.'&gt;'. $term-&gt;name .' &lt;/option&gt;';\n };\n\n // now the CHILDREN.\n foreach($children as $child) {\n $select = ($current_selected == $child-&gt;slug) ? \"selected\" : \"\"; // Note: child, not cterm\n $list_of_terms .= '&lt;option class=\"result-sub\" value=\"'.$child-&gt;slug.'\" '.$select.'&gt;'. $child-&gt;name.' &lt;/option&gt;';\n } //end foreach\n\n }\n\n /*\n * Moved this section inside your if statement. We don't want to display anything on empty terms\n */\n $list_of_terms .= '&lt;/select&gt;';\n\n }\n return $list_of_terms;\n}\n</code></pre>\n" } ]
2015/03/01
[ "https://wordpress.stackexchange.com/questions/179858", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58166/" ]
I've googled extensively and tried my best, but I just can't get the first level children of the custom taxonomy in the code below to work! It only displays the parent level. What I am trying to achieve is the following: ``` Level 1 <--- at the moment, it only displays this level Level 2 <-- I want to display this level too Level 3 <-- but NOT this level ``` This is my code so far: ``` function my_dropdown_categories( $taxonomy, $current_selected = '', $include = null ) { // Get all terms of the chosen taxonomy $terms = get_terms($taxonomy, array('orderby' => 'name')); // our content variable $list_of_terms = '<select id="location" class="selectboxSingle" name="location">'; if ( ! is_wp_error( $terms ) ) foreach($terms as $term){ // If include array set, exclude unless in array. if ( is_array( $include ) && ! in_array( $term->slug, $include ) ) continue; $select = ($current_selected == $term->slug) ? "selected" : ""; // Note: == if ($term->parent == 0 ) { // get children of current parent. // $tchildren = get_term_children($term->term_id, $taxonomy); <- gets ALL children $uchildren =get_terms( $taxonomy, array('hide_empty' => 0, 'parent' => $term->term_id )); $children = array(); foreach ($uchildren as $child) { $cterm = get_term_by( 'id', $child, $taxonomy ); // If include array set, exclude unless in array. if ( is_array( $include ) && ! in_array( $cterm->slug, $include ) ) continue; $children[$cterm->name] = $cterm; } ksort($children); // PARENT TERM if ($term->count > 0) { $list_of_terms .= '<option class ="group-result" value="'.$term->slug.'" '.$select.'>' . $term->name .' </option>'; } else { $list_of_terms .= '<option value="'.$term->slug.'" '.$select.'>'. $term->name .' </option>'; }; // now the CHILDREN. foreach($children as $child) { $select = ($current_selected == $child->slug) ? "selected" : ""; // Note: child, not cterm $list_of_terms .= '<option class="result-sub" value="'.$child->slug.'" '.$select.'>'. $child->name.' </option>'; } //end foreach } } $list_of_terms .= '</select>'; return $list_of_terms; } ``` If someone can help me with this beast, you'll be my freaken hero! **EDIT** (more info based on Pieter's answer): *This is what is being output (all parents):* Parent 1 --Parent 1 --Parent 2 --Parent 3 --Parent 4 Parent 2 --Parent 2 --Parent 1 --Parent 3 etc
You have two issues here, one is a performance issue, the other is big issue that should return a pile of errors if you enable debug The performance issue here is your first instance where you are getting the terms. It seems that your goal here is to get only top level terms, yet you get all. I would just add `'parent' => 0` to the arguments to get only top level terms. You can then drop the condition where you check `if ( $term->parent == 0 )` because all terms will be top level terms which will all have `0` as term parent, so this condition will always return true Your big issue is with this code, and I don't understand your logic here ``` $uchildren =get_terms( $taxonomy, array('hide_empty' => 0, 'parent' => $term->term_id )); $children = array(); foreach ($uchildren as $child) { $cterm = get_term_by( 'id', $child, $taxonomy ); // If include array set, exclude unless in array. if ( is_array( $include ) && ! in_array( $cterm->slug, $include ) ) continue; $children[$cterm->name] = $cterm; } ksort($children); ``` You are correct in getting your direct term children, so your declaration of `$uchildren` is fine. From there everything goes haywire * Why are you using [`get_term_by()`](http://codex.wordpress.org/Function_Reference/get_term_by) here. `$child` already holds the term properties as you have used `get_terms()` to retrieve the terms. * You are not just using `get_term_by()` wrongly here, but your arguments are invalid, and you are passing a complete object to it as well. You should consult the codex for proper use of this function. All in all, that section should be removed from your code That section should look something like this ``` $uchildren =get_terms( $taxonomy, array('hide_empty' => 0, 'parent' => $term->term_id )); $children = array(); foreach ($uchildren as $child) { if ( is_array( $include ) && ! in_array( $child->slug, $include ) ) continue; $children[$child->name] = $child; } ksort($children); ``` EDIT ---- Here is a full working code with a couple of bugs fixed. Please see my comments in code for the updates ``` function my_dropdown_categories( $taxonomy, $current_selected = '', $include = null ) { /* * Declare your variable first. Without this, your code has a bug if no terms are found */ $list_of_terms = ''; /** * Get all parent terms. Note we use 'parent' => 0 to only get top level terms * * @see get_terms * @link http://codex.wordpress.org/Function_Reference/get_terms */ $terms = get_terms( $taxonomy, array( 'orderby' => 'name', 'parent' => 0 ) ); /* * Use curlies here to enclose your statement. Also, check whether or not you have terms */ if ( $terms && ! is_wp_error( $terms ) ) { /* * Moved this section inside your if statement. We don't want to display anything on empty terms */ $list_of_terms .= '<select id="location" class="selectboxSingle" name="location">'; foreach ( $terms as $term ) { // If include array set, exclude unless in array. if ( is_array( $include ) && ! in_array( $term->slug, $include ) ) continue; $select = ($current_selected == $term->slug) ? "selected" : ""; // Note: == /* * Use the parent term term id as parent to get direct children of the term * Use child_of if you need to get all descendants of a term */ $uchildren = get_terms( $taxonomy, array('hide_empty' => 0, 'parent' => $term->term_id )); $children = array(); foreach ($uchildren as $child) { // If include array set, exclude unless in array. if ( is_array( $include ) && ! in_array( $child->slug, $include ) ) continue; $children[$child->name] = $child; } ksort($children); // PARENT TERM if ($term->count > 0) { $list_of_terms .= '<option class ="group-result" value="'.$term->slug.'" '.$select.'>' . $term->name .' </option>'; } else { $list_of_terms .= '<option value="'.$term->slug.'" '.$select.'>'. $term->name .' </option>'; }; // now the CHILDREN. foreach($children as $child) { $select = ($current_selected == $child->slug) ? "selected" : ""; // Note: child, not cterm $list_of_terms .= '<option class="result-sub" value="'.$child->slug.'" '.$select.'>'. $child->name.' </option>'; } //end foreach } /* * Moved this section inside your if statement. We don't want to display anything on empty terms */ $list_of_terms .= '</select>'; } return $list_of_terms; } ```
179,860
<p>I have a WordPress site with 65,000 registered users, about 10,000 of those users are spam bots, inactive account, hard email bonces etc.</p> <p>I have them gathered in a CSV list, how can I use that csv list to delete those users from my WordPress site?</p> <p>I haven't been able to find a plugin that does it. </p>
[ { "answer_id": 179867, "author": "ColinMcDermott", "author_id": 68355, "author_profile": "https://wordpress.stackexchange.com/users/68355", "pm_score": -1, "selected": false, "text": "<p>Have you tried the <a href=\"https://wordpress.org/plugins/stop-spammer-registrations-plugin/\" rel=\"nofollow\">Stop Spammers plugin</a></p>\n\n<p>I have found that can be pretty effective - not 100% - but good at stopping spam registrations - you can add various APIs.</p>\n\n<p>I don't think you can do the CSV thing you need specifically, but I'm pretty sure you can cut into your existing db - and prevent further spam registrations.</p>\n\n<p>Side-note, I find CloudFlare is pretty good at protecting the sign up process from bots.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>The plugin cannot delete existing users:</p>\n\n<blockquote>\n <p>Unfortunately, WordPress did not record the IP address of User registrations prior to version 5.0. This is a design flaw in WordPress. They do record the IP of comments. I cannot run a check against logins without their IP address, so you have to remove users the old fashioned way, one at a time. You might try listing the emails of all registered users, and then deleting them. You can then ask all users to re-register, but that would probably annoy your legitimate users.</p>\n</blockquote>\n" }, { "answer_id": 179874, "author": "JediTricks007", "author_id": 49017, "author_profile": "https://wordpress.stackexchange.com/users/49017", "pm_score": 1, "selected": false, "text": "<p>You could try something like this. </p>\n\n<pre><code>DELETE \nFROM wp_users \nWHERE ID in ( 5506, 5507,... );\n</code></pre>\n\n<p>Make sure to try it on a staging area first and backup your database. </p>\n" }, { "answer_id": 373708, "author": "Isacking", "author_id": 193679, "author_profile": "https://wordpress.stackexchange.com/users/193679", "pm_score": 1, "selected": false, "text": "<p>You can delete lots of users via SQL using emails:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>DELETE \nFROM wp_users \nWHERE user_email in ( '[email protected]', '[email protected]' );\n</code></pre>\n<p>You can generate list of emails in line via Excel.</p>\n<p>Or, you can exclude using Usernames too:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>DELETE \nFROM wp_users \nWHERE user_login in ( 'username1', 'username2', 'username3' );\n</code></pre>\n<p>Be sure to make a backup beforehand.</p>\n" } ]
2015/03/01
[ "https://wordpress.stackexchange.com/questions/179860", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35798/" ]
I have a WordPress site with 65,000 registered users, about 10,000 of those users are spam bots, inactive account, hard email bonces etc. I have them gathered in a CSV list, how can I use that csv list to delete those users from my WordPress site? I haven't been able to find a plugin that does it.
You could try something like this. ``` DELETE FROM wp_users WHERE ID in ( 5506, 5507,... ); ``` Make sure to try it on a staging area first and backup your database.
179,871
<p>I am having issues displaying tags only if there is tags and including php inside of it as well. This is what I tried but nothing is showing.</p> <pre><code>&lt;?php if( has_tag() ) { ?&gt; &lt;!-- Start of tags --&gt; &lt;?php echo get_the_term_list( $post-&gt;ID, 'download_tag', 'Tags ', ', ', '' ); ?&gt; &lt;!-- End of tags --&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 179876, "author": "Mark", "author_id": 59862, "author_profile": "https://wordpress.stackexchange.com/users/59862", "pm_score": 0, "selected": false, "text": "<p>Inside your condition, try this:</p>\n\n<pre><code>&lt;?php \n $var = get_the_term_list( $post-&gt;ID, 'download_tag', 'Tags ', ', ', '' );\n echo $var;\n?&gt;\n</code></pre>\n\n<p>[I have not tested this!]</p>\n" }, { "answer_id": 179887, "author": "Saurabh Shukla", "author_id": 20375, "author_profile": "https://wordpress.stackexchange.com/users/20375", "pm_score": 1, "selected": false, "text": "<p>The has_tag function doesn't do what you expect here. It actually means 'post has tag' checks if a post (or current post) has a particular tag. Something like <code>has_tag( 'self-important-tag' )</code>. <a href=\"http://codex.wordpress.org/Function_Reference/has_tag\" rel=\"nofollow\">See the codex</a> </p>\n\n<p>If you leave out the conditional and the post has no tags, get_the_termlist will echo nothing because it checks if the post has terms internally:</p>\n\n<pre><code>&lt;!-- Start of tags --&gt;\n &lt;?php echo get_the_term_list( $post-&gt;ID, 'download_tag', 'Tags ', ', ', '' ); ?&gt;\n&lt;!-- End of tags --&gt;\n</code></pre>\n" } ]
2015/03/02
[ "https://wordpress.stackexchange.com/questions/179871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49017/" ]
I am having issues displaying tags only if there is tags and including php inside of it as well. This is what I tried but nothing is showing. ``` <?php if( has_tag() ) { ?> <!-- Start of tags --> <?php echo get_the_term_list( $post->ID, 'download_tag', 'Tags ', ', ', '' ); ?> <!-- End of tags --> <?php } ?> ```
The has\_tag function doesn't do what you expect here. It actually means 'post has tag' checks if a post (or current post) has a particular tag. Something like `has_tag( 'self-important-tag' )`. [See the codex](http://codex.wordpress.org/Function_Reference/has_tag) If you leave out the conditional and the post has no tags, get\_the\_termlist will echo nothing because it checks if the post has terms internally: ``` <!-- Start of tags --> <?php echo get_the_term_list( $post->ID, 'download_tag', 'Tags ', ', ', '' ); ?> <!-- End of tags --> ```
179,883
<p>I used simple-fields plugin for one addition field(premium posts) and now I need to change the popular post widget. I need to get all popular post exclude premium post.</p> <p>What I have tried so far,</p> <p>original query,</p> <pre><code>$popularposts = new WP_Query('showposts=5&amp;meta_key=post_views_count&amp;orderby=meta_value_num&amp;order=DESC&amp;ignore_sticky_posts=1') </code></pre> <p>edited query,</p> <pre><code>$args1 = array( 'showposts' =&gt; 5, 'ignore_sticky_posts' =&gt; 1, 'meta_query' =&gt; array( array( 'key' =&gt; 'post_views_count', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; DESC ), array( 'key' =&gt; '_simple_fields_fieldGroupID_2_fieldID_1_numInSet_0', 'compare' =&gt;'NOT EXISTS' ), ), ); $popularposts = new WP_Query($args1); </code></pre> <p>But it doesn't provide expected results, it exclude premium posts(field : <code>_simple_fields_fieldGroupID_2_fieldID_1_numInSet_0</code>) but it doesn't sort by <code>post_view_counts</code>.</p> <p>Any help would be appreciate..</p>
[ { "answer_id": 179876, "author": "Mark", "author_id": 59862, "author_profile": "https://wordpress.stackexchange.com/users/59862", "pm_score": 0, "selected": false, "text": "<p>Inside your condition, try this:</p>\n\n<pre><code>&lt;?php \n $var = get_the_term_list( $post-&gt;ID, 'download_tag', 'Tags ', ', ', '' );\n echo $var;\n?&gt;\n</code></pre>\n\n<p>[I have not tested this!]</p>\n" }, { "answer_id": 179887, "author": "Saurabh Shukla", "author_id": 20375, "author_profile": "https://wordpress.stackexchange.com/users/20375", "pm_score": 1, "selected": false, "text": "<p>The has_tag function doesn't do what you expect here. It actually means 'post has tag' checks if a post (or current post) has a particular tag. Something like <code>has_tag( 'self-important-tag' )</code>. <a href=\"http://codex.wordpress.org/Function_Reference/has_tag\" rel=\"nofollow\">See the codex</a> </p>\n\n<p>If you leave out the conditional and the post has no tags, get_the_termlist will echo nothing because it checks if the post has terms internally:</p>\n\n<pre><code>&lt;!-- Start of tags --&gt;\n &lt;?php echo get_the_term_list( $post-&gt;ID, 'download_tag', 'Tags ', ', ', '' ); ?&gt;\n&lt;!-- End of tags --&gt;\n</code></pre>\n" } ]
2015/03/02
[ "https://wordpress.stackexchange.com/questions/179883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
I used simple-fields plugin for one addition field(premium posts) and now I need to change the popular post widget. I need to get all popular post exclude premium post. What I have tried so far, original query, ``` $popularposts = new WP_Query('showposts=5&meta_key=post_views_count&orderby=meta_value_num&order=DESC&ignore_sticky_posts=1') ``` edited query, ``` $args1 = array( 'showposts' => 5, 'ignore_sticky_posts' => 1, 'meta_query' => array( array( 'key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => DESC ), array( 'key' => '_simple_fields_fieldGroupID_2_fieldID_1_numInSet_0', 'compare' =>'NOT EXISTS' ), ), ); $popularposts = new WP_Query($args1); ``` But it doesn't provide expected results, it exclude premium posts(field : `_simple_fields_fieldGroupID_2_fieldID_1_numInSet_0`) but it doesn't sort by `post_view_counts`. Any help would be appreciate..
The has\_tag function doesn't do what you expect here. It actually means 'post has tag' checks if a post (or current post) has a particular tag. Something like `has_tag( 'self-important-tag' )`. [See the codex](http://codex.wordpress.org/Function_Reference/has_tag) If you leave out the conditional and the post has no tags, get\_the\_termlist will echo nothing because it checks if the post has terms internally: ``` <!-- Start of tags --> <?php echo get_the_term_list( $post->ID, 'download_tag', 'Tags ', ', ', '' ); ?> <!-- End of tags --> ```
179,892
<p>i have created custom post type</p> <p>my problem is:</p> <p>in admin column, posts are sorted by ID</p> <p>how can change it to date. In other words, i want to sort post by recently</p>
[ { "answer_id": 327613, "author": "Ehsan", "author_id": 54976, "author_profile": "https://wordpress.stackexchange.com/users/54976", "pm_score": 2, "selected": false, "text": "<pre><code>add_action( 'pre_get_posts', 'change_post_sort', 1 );\nfunction change_post_sort( $query ) {\n if ( is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'order' , 'DESC' );\n $query-&gt;set( 'orderby', 'modified');\n return $query;\n}\n</code></pre>\n" }, { "answer_id": 327614, "author": "Mahmood Afzalzadeh", "author_id": 160498, "author_profile": "https://wordpress.stackexchange.com/users/160498", "pm_score": 2, "selected": true, "text": "<p>You must add this part to function.php:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'example_func', 1 );\n function example_func( $query ) {\n if ( is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'order' , 'DESC' );\n }\n return $query;\n}\n</code></pre>\n" } ]
2015/03/02
[ "https://wordpress.stackexchange.com/questions/179892", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54976/" ]
i have created custom post type my problem is: in admin column, posts are sorted by ID how can change it to date. In other words, i want to sort post by recently
You must add this part to function.php: ``` add_action( 'pre_get_posts', 'example_func', 1 ); function example_func( $query ) { if ( is_admin() && $query->is_main_query() ) { $query->set( 'order' , 'DESC' ); } return $query; } ```
179,908
<p>i have created user vote that can vote users or author of posts. so for example have 4 users which looks:</p> <ol> <li><p>user --- ID=1 --- META KEY='_thumbs_rating_up' --- META VALUE='13'</p></li> <li><p>user --- ID=2 --- META KEY='_thumbs_rating_up' --- META VALUE='17'</p></li> <li><p>user --- ID=3 --- META KEY='_thumbs_rating_up' --- META VALUE='8'</p></li> <li><p>user --- ID=4 --- META KEY='_thumbs_rating_up' --- META VALUE='241'</p></li> </ol> <p>So i must order these users by user meta key and meta value from heighest to lowwer. So i have these code now but order is not correct:</p> <pre><code>&lt;?php $args = array( 'role' =&gt; 'Seller', 'meta_key' =&gt; '_thumbs_rating_up', 'orderby' =&gt; 'meta_value_num' ); // The Query $user_query = new WP_User_Query( $args ); // User Loop if ( ! empty( $user_query-&gt;results ) ) { foreach ( $user_query-&gt;results as $user ) { echo '&lt;p&gt;' . get_avatar( $user-&gt;ID, 32 ) . '&lt;/p&gt;'; echo '&lt;p&gt;' . get_user_meta($user-&gt;ID, '_thumbs_rating_up', true). '&lt;/p&gt;'; echo '&lt;p&gt;' . $user-&gt;display_name . '&lt;/p&gt;'; } } else { echo 'No users found.'; } ?&gt; </code></pre> <p>what i do wrong or simply can not order my custom meta key??????</p> <ul> <li>i find the post here which is similar but i dont know how can i help with these answers: <a href="https://wordpress.stackexchange.com/questions/149342/sort-users-by-meta-value-num">Sort users by meta_value_num</a></li> </ul>
[ { "answer_id": 327613, "author": "Ehsan", "author_id": 54976, "author_profile": "https://wordpress.stackexchange.com/users/54976", "pm_score": 2, "selected": false, "text": "<pre><code>add_action( 'pre_get_posts', 'change_post_sort', 1 );\nfunction change_post_sort( $query ) {\n if ( is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'order' , 'DESC' );\n $query-&gt;set( 'orderby', 'modified');\n return $query;\n}\n</code></pre>\n" }, { "answer_id": 327614, "author": "Mahmood Afzalzadeh", "author_id": 160498, "author_profile": "https://wordpress.stackexchange.com/users/160498", "pm_score": 2, "selected": true, "text": "<p>You must add this part to function.php:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'example_func', 1 );\n function example_func( $query ) {\n if ( is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'order' , 'DESC' );\n }\n return $query;\n}\n</code></pre>\n" } ]
2015/03/02
[ "https://wordpress.stackexchange.com/questions/179908", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52391/" ]
i have created user vote that can vote users or author of posts. so for example have 4 users which looks: 1. user --- ID=1 --- META KEY='\_thumbs\_rating\_up' --- META VALUE='13' 2. user --- ID=2 --- META KEY='\_thumbs\_rating\_up' --- META VALUE='17' 3. user --- ID=3 --- META KEY='\_thumbs\_rating\_up' --- META VALUE='8' 4. user --- ID=4 --- META KEY='\_thumbs\_rating\_up' --- META VALUE='241' So i must order these users by user meta key and meta value from heighest to lowwer. So i have these code now but order is not correct: ``` <?php $args = array( 'role' => 'Seller', 'meta_key' => '_thumbs_rating_up', 'orderby' => 'meta_value_num' ); // The Query $user_query = new WP_User_Query( $args ); // User Loop if ( ! empty( $user_query->results ) ) { foreach ( $user_query->results as $user ) { echo '<p>' . get_avatar( $user->ID, 32 ) . '</p>'; echo '<p>' . get_user_meta($user->ID, '_thumbs_rating_up', true). '</p>'; echo '<p>' . $user->display_name . '</p>'; } } else { echo 'No users found.'; } ?> ``` what i do wrong or simply can not order my custom meta key?????? * i find the post here which is similar but i dont know how can i help with these answers: [Sort users by meta\_value\_num](https://wordpress.stackexchange.com/questions/149342/sort-users-by-meta-value-num)
You must add this part to function.php: ``` add_action( 'pre_get_posts', 'example_func', 1 ); function example_func( $query ) { if ( is_admin() && $query->is_main_query() ) { $query->set( 'order' , 'DESC' ); } return $query; } ```
179,955
<p>In my post page, used gallery on post plugin to display images , while i m trying to retrieve the post content -used the_content , but showing the plugin images also. how i get text editor content only? </p>
[ { "answer_id": 179997, "author": "DINESH BHIMANI", "author_id": 56382, "author_profile": "https://wordpress.stackexchange.com/users/56382", "pm_score": -1, "selected": false, "text": "<p>use this code to show only content of post</p>\n\n<pre><code> $args = array(\n 'order' =&gt; 'ASC'\n);\nquery_posts( $args );\n\nwhile ( have_posts() ) : the_post();\n// get only post of content not work plug-in short code\n$post_7 = get_post(get_the_ID()); \necho $title = $post_7-&gt;post_content;\n\nendwhile;\n\n// Reset Query\nwp_reset_query();\n</code></pre>\n" }, { "answer_id": 180006, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php while (have_posts()) : the_post(); ?&gt;\n&lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;\n&lt;?php the_content(); ?&gt;\n&lt;?php endwhile; ?&gt;\n</code></pre>\n" } ]
2015/03/02
[ "https://wordpress.stackexchange.com/questions/179955", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68444/" ]
In my post page, used gallery on post plugin to display images , while i m trying to retrieve the post content -used the\_content , but showing the plugin images also. how i get text editor content only?
use this code to show only content of post ``` $args = array( 'order' => 'ASC' ); query_posts( $args ); while ( have_posts() ) : the_post(); // get only post of content not work plug-in short code $post_7 = get_post(get_the_ID()); echo $title = $post_7->post_content; endwhile; // Reset Query wp_reset_query(); ```
179,995
<p>I want to make an author box like this : <img src="https://i.stack.imgur.com/fgDNP.png" alt="enter image description here"></p> <pre><code>&lt;table style="border: solid 1px #ffffff;width:100%;"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;h3&gt;&lt;b&gt;&lt;span style="color: #555; "&gt;About Author&lt;/span&gt;&amp;nbsp;&lt;/b&gt; &lt;input type="hidden" name="stats" value="2498"&gt; &lt;/h3&gt;you can be an author too, join mhktricks and show you skills&lt;/td&gt; &lt;td style="border: solid 1px #ffffff;" align="right"&gt; &lt;a href="http://mhktricks.net/user-registration/" target="_blank"&gt; &lt;input class="p2graybtn" style="height: 26px; width:150px;" type="button" value="Join Us"&gt; &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;hr&gt; &lt;table style="border: solid 1px #ffffff;"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;?php echo get_avatar( get_the_author_meta( 'user_email' ), 70 ); ?&gt; &lt;/td&gt; &lt;td style="border: solid 1px #ffffff;"&gt; &lt;table style="border: solid 1px #ffffff;"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;span style="color: #555;font-size:20px;font-family: Open Sans;font-weight: 400;font-style: normal;text-decoration: none;"&gt; &lt;?php echo get_the_author(); ?&gt; &lt;/span&gt; &lt;br&gt;&lt;div style="margin-left:1px;"&gt; &lt;?php echo get_author_role(); ?&gt; &lt;span style="position:relative;top:1px;margin-left:5px;"&gt;&lt;img src="http://i2.wp.com/codex.onhax.net/img/verified.png" height="12" width="12"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;td style="border: solid 1px #ffffff;"&gt; &lt;div style="margin-left: 3px;margin-top: -17px;border: #B8B8B8 1px solid;border-radius:2px;padding: 0px 5px 0px 5px;font-size:10px;"&gt; &lt;?php the_author_posts(); ?&gt; POSTS&lt;/div&gt;'; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;&lt;div style="margin-top:-12px;"&gt;&amp;nbsp; &lt;/div&gt; &lt;div style="margin-left:3px;margin-top:2px;padding-right:60px;"&gt; &lt;?php the_author_meta( 'description' ); ?&gt; &lt;a class="author-link" href="&lt;?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?&gt;" rel="author"&gt; View all posts by me &lt;?php get_the_author(); ?&gt; &lt;span class="meta-nav"&gt;&amp;rarr;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;hr color="white"&gt; &lt;hr color="white"&gt; &lt;table style="border: solid 1px #ffffff;width:100%;"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;h3&gt;&lt;b&gt;&lt;span style="color: #555; "&gt;Discussion&lt;/span&gt;&lt;/b&gt;&lt;/h3&gt; share your knowledge.mind to help others&lt;/td&gt; &lt;td style="border: solid 1px #ffffff;" align="right"&gt; &lt;a href="#" class="show-comments"&gt; &lt;input class="p2graybtn" style="height: 26px;" type="button" value="Toggle Comments"&gt; &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I have made upto this but how to insert it in every post ?</p>
[ { "answer_id": 179996, "author": "Ruturaj", "author_id": 43266, "author_profile": "https://wordpress.stackexchange.com/users/43266", "pm_score": 1, "selected": false, "text": "<p>I've not tested your code; but assuming it's correct and working well, edit your <code>single.php</code> file and insert this code just after the point where you end your post content and before the Comment Section starts. </p>\n\n<p>I'd suggest to write this Author Box code in a separate file and then use <code>get_template_part</code> to insert the Author Box section in your Post. See <a href=\"http://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">this function Reference page</a> if you're new to the <code>get_template_part</code> function.</p>\n" }, { "answer_id": 179998, "author": "jogesh_pi", "author_id": 13331, "author_profile": "https://wordpress.stackexchange.com/users/13331", "pm_score": 0, "selected": false, "text": "<p>you can do with <code>the_content</code> filter. </p>\n\n<pre><code>add_filter( 'the_content', 'my_the_content_filter', 20 );\nfunction my_the_content_filter( $content ) {\n\n if ( is_single() ) {\n $content = $content . \"YOUR_HTML_FOR_BOX\";\n }\n\n // Returns the content.\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 180010, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": 0, "selected": false, "text": "<p>Just add bellow code into function.php file.</p>\n\n<pre><code>function add_author_content($content)\n{\n $author = get_the_author();\n $content = $content.' - '.$author;\n return $content;\n}\nadd_filter('the_content', 'add_author_content');\n</code></pre>\n" } ]
2015/03/03
[ "https://wordpress.stackexchange.com/questions/179995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67503/" ]
I want to make an author box like this : ![enter image description here](https://i.stack.imgur.com/fgDNP.png) ``` <table style="border: solid 1px #ffffff;width:100%;"> <tbody> <tr> <td> <h3><b><span style="color: #555; ">About Author</span>&nbsp;</b> <input type="hidden" name="stats" value="2498"> </h3>you can be an author too, join mhktricks and show you skills</td> <td style="border: solid 1px #ffffff;" align="right"> <a href="http://mhktricks.net/user-registration/" target="_blank"> <input class="p2graybtn" style="height: 26px; width:150px;" type="button" value="Join Us"> </a> </td> </tr> </tbody> </table> <hr> <table style="border: solid 1px #ffffff;"> <tbody> <tr> <td> <?php echo get_avatar( get_the_author_meta( 'user_email' ), 70 ); ?> </td> <td style="border: solid 1px #ffffff;"> <table style="border: solid 1px #ffffff;"> <tbody> <tr> <td> <span style="color: #555;font-size:20px;font-family: Open Sans;font-weight: 400;font-style: normal;text-decoration: none;"> <?php echo get_the_author(); ?> </span> <br><div style="margin-left:1px;"> <?php echo get_author_role(); ?> <span style="position:relative;top:1px;margin-left:5px;"><img src="http://i2.wp.com/codex.onhax.net/img/verified.png" height="12" width="12"></span> </div> </td> <td style="border: solid 1px #ffffff;"> <div style="margin-left: 3px;margin-top: -17px;border: #B8B8B8 1px solid;border-radius:2px;padding: 0px 5px 0px 5px;font-size:10px;"> <?php the_author_posts(); ?> POSTS</div>'; </td> </tr> </tbody> </table><div style="margin-top:-12px;">&nbsp; </div> <div style="margin-left:3px;margin-top:2px;padding-right:60px;"> <?php the_author_meta( 'description' ); ?> <a class="author-link" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"> View all posts by me <?php get_the_author(); ?> <span class="meta-nav">&rarr;</span> </a> </div> </td> </tr> </tbody> </table> <hr color="white"> <hr color="white"> <table style="border: solid 1px #ffffff;width:100%;"> <tbody> <tr> <td> <h3><b><span style="color: #555; ">Discussion</span></b></h3> share your knowledge.mind to help others</td> <td style="border: solid 1px #ffffff;" align="right"> <a href="#" class="show-comments"> <input class="p2graybtn" style="height: 26px;" type="button" value="Toggle Comments"> </a> </td> </tr> </tbody> </table> ``` I have made upto this but how to insert it in every post ?
I've not tested your code; but assuming it's correct and working well, edit your `single.php` file and insert this code just after the point where you end your post content and before the Comment Section starts. I'd suggest to write this Author Box code in a separate file and then use `get_template_part` to insert the Author Box section in your Post. See [this function Reference page](http://codex.wordpress.org/Function_Reference/get_template_part) if you're new to the `get_template_part` function.
180,080
<p>I got a little obstruction. I have a free theme, which I like, but I found out that in the footer there are too many commercial links (Let me say spammy links). I want to keep the credits to the author. But I need to remove the ''spam'' links. I've tried many things for few hour by now, but I am not familiar with PHP so I stuck. Here is my code in functions.php</p> <pre><code>function wp_initialize_the_theme_load() { if (!function_exists("wp_initialize_the_theme")) { wp_initialize_the_theme_message(); die; } } function wp_initialize_the_theme_finish() { $uri = strtolower($_SERVER["REQUEST_URI"]); if(is_admin() || substr_count($uri, "wp-admin") &gt; 0 || substr_count($uri, "wp-login") &gt; 0 ) { /* */ } else { $l = ' | Theme Designed by: &lt;?php echo wp_theme_credits(0); ?&gt; | Thanks to &lt;?php echo wp_theme_credits(1); ?&gt;, &lt;?php echo wp_theme_credits(2); ?&gt; and &lt;?php echo wp_theme_credits(3); ?&gt;'; $f = dirname(__file__) . "/footer.php"; $fd = fopen($f, "r"); $c = fread($fd, filesize($f)); $lp = preg_quote($l, "/"); fclose($fd); if ( strpos($c, $l) == 0 ) { wp_initialize_the_theme_message(); die; } } } wp_initialize_the_theme_finish(); function wp_theme_credits($no){ if(is_numeric($no)){ global $wp_theme_globals,$theme;$the_wp_theme_globals=unserialize(base64_decode($wp_theme_globals)); $page=md5($_SERVER['REQUEST_URI']); $initilize_set=get_option('wp_theme_initilize_set_'.str_replace(' ','_',strtolower(trim($theme-&gt;theme_name)))); if(!is_array($initilize_set[$page])) { $initilize_set=wp_initialize_the_theme_go($page); } $ret='&lt;a href="'.$the_wp_theme_globals[$no][$initilize_set[$page][$no]].'"&gt;'.$initilize_set[$page][$no].'&lt;/a&gt;'; return $ret; } } </code></pre> <p>Thank you in advance. </p>
[ { "answer_id": 179996, "author": "Ruturaj", "author_id": 43266, "author_profile": "https://wordpress.stackexchange.com/users/43266", "pm_score": 1, "selected": false, "text": "<p>I've not tested your code; but assuming it's correct and working well, edit your <code>single.php</code> file and insert this code just after the point where you end your post content and before the Comment Section starts. </p>\n\n<p>I'd suggest to write this Author Box code in a separate file and then use <code>get_template_part</code> to insert the Author Box section in your Post. See <a href=\"http://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">this function Reference page</a> if you're new to the <code>get_template_part</code> function.</p>\n" }, { "answer_id": 179998, "author": "jogesh_pi", "author_id": 13331, "author_profile": "https://wordpress.stackexchange.com/users/13331", "pm_score": 0, "selected": false, "text": "<p>you can do with <code>the_content</code> filter. </p>\n\n<pre><code>add_filter( 'the_content', 'my_the_content_filter', 20 );\nfunction my_the_content_filter( $content ) {\n\n if ( is_single() ) {\n $content = $content . \"YOUR_HTML_FOR_BOX\";\n }\n\n // Returns the content.\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 180010, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": 0, "selected": false, "text": "<p>Just add bellow code into function.php file.</p>\n\n<pre><code>function add_author_content($content)\n{\n $author = get_the_author();\n $content = $content.' - '.$author;\n return $content;\n}\nadd_filter('the_content', 'add_author_content');\n</code></pre>\n" } ]
2015/03/03
[ "https://wordpress.stackexchange.com/questions/180080", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I got a little obstruction. I have a free theme, which I like, but I found out that in the footer there are too many commercial links (Let me say spammy links). I want to keep the credits to the author. But I need to remove the ''spam'' links. I've tried many things for few hour by now, but I am not familiar with PHP so I stuck. Here is my code in functions.php ``` function wp_initialize_the_theme_load() { if (!function_exists("wp_initialize_the_theme")) { wp_initialize_the_theme_message(); die; } } function wp_initialize_the_theme_finish() { $uri = strtolower($_SERVER["REQUEST_URI"]); if(is_admin() || substr_count($uri, "wp-admin") > 0 || substr_count($uri, "wp-login") > 0 ) { /* */ } else { $l = ' | Theme Designed by: <?php echo wp_theme_credits(0); ?> | Thanks to <?php echo wp_theme_credits(1); ?>, <?php echo wp_theme_credits(2); ?> and <?php echo wp_theme_credits(3); ?>'; $f = dirname(__file__) . "/footer.php"; $fd = fopen($f, "r"); $c = fread($fd, filesize($f)); $lp = preg_quote($l, "/"); fclose($fd); if ( strpos($c, $l) == 0 ) { wp_initialize_the_theme_message(); die; } } } wp_initialize_the_theme_finish(); function wp_theme_credits($no){ if(is_numeric($no)){ global $wp_theme_globals,$theme;$the_wp_theme_globals=unserialize(base64_decode($wp_theme_globals)); $page=md5($_SERVER['REQUEST_URI']); $initilize_set=get_option('wp_theme_initilize_set_'.str_replace(' ','_',strtolower(trim($theme->theme_name)))); if(!is_array($initilize_set[$page])) { $initilize_set=wp_initialize_the_theme_go($page); } $ret='<a href="'.$the_wp_theme_globals[$no][$initilize_set[$page][$no]].'">'.$initilize_set[$page][$no].'</a>'; return $ret; } } ``` Thank you in advance.
I've not tested your code; but assuming it's correct and working well, edit your `single.php` file and insert this code just after the point where you end your post content and before the Comment Section starts. I'd suggest to write this Author Box code in a separate file and then use `get_template_part` to insert the Author Box section in your Post. See [this function Reference page](http://codex.wordpress.org/Function_Reference/get_template_part) if you're new to the `get_template_part` function.
180,087
<p>hello i have post_type "product" and taxonomy "price" can someone help me to query that custom post type with the selected taxonomy?</p> <p>my current code is like this</p> <pre><code>&lt;?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); $args = array( 'post_type' =&gt; 'product', 'posts_per_page' =&gt; 5, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'productcategories', 'terms' =&gt; $term-&gt;name ) ) ); query_posts($args); print_r($args); ?&gt; </code></pre> <p>but nothing on result, can someone help me? thank you</p>
[ { "answer_id": 179996, "author": "Ruturaj", "author_id": 43266, "author_profile": "https://wordpress.stackexchange.com/users/43266", "pm_score": 1, "selected": false, "text": "<p>I've not tested your code; but assuming it's correct and working well, edit your <code>single.php</code> file and insert this code just after the point where you end your post content and before the Comment Section starts. </p>\n\n<p>I'd suggest to write this Author Box code in a separate file and then use <code>get_template_part</code> to insert the Author Box section in your Post. See <a href=\"http://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">this function Reference page</a> if you're new to the <code>get_template_part</code> function.</p>\n" }, { "answer_id": 179998, "author": "jogesh_pi", "author_id": 13331, "author_profile": "https://wordpress.stackexchange.com/users/13331", "pm_score": 0, "selected": false, "text": "<p>you can do with <code>the_content</code> filter. </p>\n\n<pre><code>add_filter( 'the_content', 'my_the_content_filter', 20 );\nfunction my_the_content_filter( $content ) {\n\n if ( is_single() ) {\n $content = $content . \"YOUR_HTML_FOR_BOX\";\n }\n\n // Returns the content.\n return $content;\n}\n</code></pre>\n" }, { "answer_id": 180010, "author": "Jakir Hossain", "author_id": 68472, "author_profile": "https://wordpress.stackexchange.com/users/68472", "pm_score": 0, "selected": false, "text": "<p>Just add bellow code into function.php file.</p>\n\n<pre><code>function add_author_content($content)\n{\n $author = get_the_author();\n $content = $content.' - '.$author;\n return $content;\n}\nadd_filter('the_content', 'add_author_content');\n</code></pre>\n" } ]
2015/03/04
[ "https://wordpress.stackexchange.com/questions/180087", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68523/" ]
hello i have post\_type "product" and taxonomy "price" can someone help me to query that custom post type with the selected taxonomy? my current code is like this ``` <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); $args = array( 'post_type' => 'product', 'posts_per_page' => 5, 'tax_query' => array( array( 'taxonomy' => 'productcategories', 'terms' => $term->name ) ) ); query_posts($args); print_r($args); ?> ``` but nothing on result, can someone help me? thank you
I've not tested your code; but assuming it's correct and working well, edit your `single.php` file and insert this code just after the point where you end your post content and before the Comment Section starts. I'd suggest to write this Author Box code in a separate file and then use `get_template_part` to insert the Author Box section in your Post. See [this function Reference page](http://codex.wordpress.org/Function_Reference/get_template_part) if you're new to the `get_template_part` function.
180,132
<p>In a multisite network, when you change the main email address in Settings / General, Wordpress sends an email that must be confirmed by the new email recipient.</p> <p>I need to avoid or customize the message that is being sent but can't figure out how.</p> <p>The function responsible for sending this email is not pluggable, as show bellow:</p> <pre><code>/** * Sends an email when a site administrator email address is changed. * * @since 3.0.0 * * @param string $old_value The old email address. Not currently used. * @param string $value The new email address. */ function update_option_new_admin_email( $old_value, $value ) { if ( $value == get_option( 'admin_email' ) || !is_email( $value ) ) return; $hash = md5( $value. time() .mt_rand() ); $new_admin_email = array( 'hash' =&gt; $hash, 'newemail' =&gt; $value ); update_option( 'adminhash', $new_admin_email ); $email_text = __( 'Dear user, You recently requested to have the administration email address on your site changed. If this is correct, please click on the following link to change it: ###ADMIN_URL### You can safely ignore and delete this email if you do not want to take this action. This email has been sent to ###EMAIL### Regards, All at ###SITENAME### ###SITEURL###' ); </code></pre> <p>This function continues and have a few filters to change some vars, but no way to customise the message itself.</p> <p>Do you know any way to avoid this notification from being necessary in multisite, or at least to be able to override the message it sends?</p>
[ { "answer_id": 180140, "author": "Luis Martins", "author_id": 62160, "author_profile": "https://wordpress.stackexchange.com/users/62160", "pm_score": 0, "selected": false, "text": "<p>As indicated by @David Gard, this can easily be done:</p>\n\n<pre><code>&lt;?php\n\nremove_action( 'add_option_new_admin_email', 'update_option_new_admin_email' );\nremove_action( 'update_option_new_admin_email', 'update_option_new_admin_email' );\n\n/**\n * Disable the confirmation notices when an administrator\n * changes their email address.\n *\n * @see http://codex.wordpress.com/Function_Reference/update_option_new_admin_email\n */\nfunction wpdocs_update_option_new_admin_email( $old_value, $value ) {\n\n update_option( 'admin_email', $value );\n}\nadd_action( 'add_option_new_admin_email', 'wpdocs_update_option_new_admin_email' );\nadd_action( 'update_option_new_admin_email', 'wpdocs_update_option_new_admin_email' );\n\n?&gt;\n</code></pre>\n\n<p>EDIT: The Codex documentation is marked as \"Needs Update\" and I've confirmed it doesn't work in the current form.</p>\n" }, { "answer_id": 180393, "author": "David Gard", "author_id": 10097, "author_profile": "https://wordpress.stackexchange.com/users/10097", "pm_score": 2, "selected": true, "text": "<p>It seems that my edit to your answer was declined, so here you go.</p>\n\n<p>All that was missing was the <code>$priority</code> and <code>$accepted_args</code> parameters for the <code>add_action()</code> calls, and the the fixed code below should accomplish what you require.</p>\n\n<pre><code>remove_action( 'add_option_new_admin_email', 'update_option_new_admin_email' );\nremove_action( 'update_option_new_admin_email', 'update_option_new_admin_email' );\n\n/**\n * Disable the confirmation notices when an administrator\n * changes their email address.\n *\n * @see http://codex.wordpress.com/Function_Reference/update_option_new_admin_email\n */\nfunction wpdocs_update_option_new_admin_email( $old_value, $value ) {\n\n update_option( 'admin_email', $value );\n}\nadd_action( 'add_option_new_admin_email', 'wpdocs_update_option_new_admin_email', 10, 2 );\nadd_action( 'update_option_new_admin_email', 'wpdocs_update_option_new_admin_email', 10, 2 );\n</code></pre>\n" } ]
2015/03/04
[ "https://wordpress.stackexchange.com/questions/180132", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62160/" ]
In a multisite network, when you change the main email address in Settings / General, Wordpress sends an email that must be confirmed by the new email recipient. I need to avoid or customize the message that is being sent but can't figure out how. The function responsible for sending this email is not pluggable, as show bellow: ``` /** * Sends an email when a site administrator email address is changed. * * @since 3.0.0 * * @param string $old_value The old email address. Not currently used. * @param string $value The new email address. */ function update_option_new_admin_email( $old_value, $value ) { if ( $value == get_option( 'admin_email' ) || !is_email( $value ) ) return; $hash = md5( $value. time() .mt_rand() ); $new_admin_email = array( 'hash' => $hash, 'newemail' => $value ); update_option( 'adminhash', $new_admin_email ); $email_text = __( 'Dear user, You recently requested to have the administration email address on your site changed. If this is correct, please click on the following link to change it: ###ADMIN_URL### You can safely ignore and delete this email if you do not want to take this action. This email has been sent to ###EMAIL### Regards, All at ###SITENAME### ###SITEURL###' ); ``` This function continues and have a few filters to change some vars, but no way to customise the message itself. Do you know any way to avoid this notification from being necessary in multisite, or at least to be able to override the message it sends?
It seems that my edit to your answer was declined, so here you go. All that was missing was the `$priority` and `$accepted_args` parameters for the `add_action()` calls, and the the fixed code below should accomplish what you require. ``` remove_action( 'add_option_new_admin_email', 'update_option_new_admin_email' ); remove_action( 'update_option_new_admin_email', 'update_option_new_admin_email' ); /** * Disable the confirmation notices when an administrator * changes their email address. * * @see http://codex.wordpress.com/Function_Reference/update_option_new_admin_email */ function wpdocs_update_option_new_admin_email( $old_value, $value ) { update_option( 'admin_email', $value ); } add_action( 'add_option_new_admin_email', 'wpdocs_update_option_new_admin_email', 10, 2 ); add_action( 'update_option_new_admin_email', 'wpdocs_update_option_new_admin_email', 10, 2 ); ```
180,153
<p>I am trying to implement an archive for a custom post type:</p> <pre><code>http://mywebsite:8888/about-us/client-news/2015/03/ </code></pre> <p>The problem is that it keeps serving me a 404 page and I cannot work out what page template its failing to find. I have tried turning on debug and a number of other steps</p> <p>The registration:</p> <pre><code>function client_news() { $labels = array( 'name' =&gt; _x("Client News", "post type general name"), 'singular_name' =&gt; _x("Client News Item", "post type singular name"), 'menu_name' =&gt; 'Client News', 'add_new' =&gt; _x("Add New", "news item"), 'add_new_item' =&gt; __("Add New News Item"), 'edit_item' =&gt; __("Edit News Item"), 'new_item' =&gt; __("New News Item"), 'view_item' =&gt; __("View News Item"), 'search_items' =&gt; __("Search Client News"), 'not_found' =&gt; __("No Useful Items Found"), 'not_found_in_trash' =&gt; __("No Useful Items Found in Trash"), 'parent_item_colon' =&gt; '' ); // Register post type register_post_type('clientnews' , array( 'labels' =&gt; $labels, 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'news' ), 'supports' =&gt; array('title', 'editor', 'thumbnail') ) ); } add_action( 'init', 'client_news', 0 ); </code></pre> <p>Archive loop is as follows:</p> <pre><code>&lt;ul class="news_archive"&gt; &lt;?php add_filter( 'get_archives_link', 'get_archives_clientnews_link', 10, 2 ); wp_get_archives( array( 'post_type' =&gt; 'clientnews', 'type' =&gt; 'monthly' ) ); remove_filter( 'get_archives_link', 'get_archives_clientnews_link', 10, 2 ); ?&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 180170, "author": "Fiaz Husyn", "author_id": 62739, "author_profile": "https://wordpress.stackexchange.com/users/62739", "pm_score": 0, "selected": false, "text": "<p>Try visiting : </p>\n\n<pre><code>http://mywebsite:8888/about-us/news/2015/03/\n</code></pre>\n\n<p>You are using <code>slug =&gt; 'news'</code> so <code>'client-news'</code> will give you an error</p>\n" }, { "answer_id": 180234, "author": "Eth", "author_id": 68565, "author_profile": "https://wordpress.stackexchange.com/users/68565", "pm_score": 2, "selected": true, "text": "<p>I have managed to resolve this by adding in a custom rewrite into the functions file:</p>\n\n<pre><code>// Add custom rewrite rules to handle things like years in custom post archives\nfunction add_rewrite_rules($aRules) {\n $aNewRules = array(\n 'news/([0-9]{4})/([0-9]{2})/page/?([0-9]{1,})/?$' =&gt; 'index.php?post_type=clientnews&amp;year=$matches[1]&amp;monthnum=$matches[2]&amp;paged=$matches[3]',\n 'news/([0-9]{4})/([0-9]{2})/?$' =&gt; 'index.php?post_type=clientnews&amp;year=$matches[1]&amp;monthnum=$matches[2]',\n 'about-us/other-news/([0-9]{4})/([0-9]{2})/page/?([0-9]{1,})/?$' =&gt; 'index.php?post_type=othernews&amp;year=$matches[1]&amp;monthnum=$matches[2]&amp;paged=$matches[3]',\n 'about-us/other-news/([0-9]{4})/([0-9]{2})/?$' =&gt; 'index.php?post_type=othernews&amp;year=$matches[1]&amp;monthnum=$matches[2]'\n );\n $aRules = $aNewRules + $aRules;\n return $aRules;\n}\n\n// hook add_rewrite_rules function into rewrite_rules_array\nadd_filter('rewrite_rules_array', 'add_rewrite_rules');\n</code></pre>\n\n<p>Then in the archive page I changed the query to:</p>\n\n<pre><code>$aParts = explode( '/', $_SERVER['REQUEST_URI'] );\n\n$iYear = get_query_var('year');\n$iMonth = get_query_var('monthnum');\n\nif( $iMonth &lt;= 0 &amp;&amp; $iYear &gt; 0 )\n{\n $iMonth = $aParts[ 4 ];\n}\n\n$news = new WP_Query('showposts=6&amp;post_type=othernews&amp;paged='. $paged . '&amp;year=' . $iYear . '&amp;monthnum=' . $iMonth );\n</code></pre>\n" } ]
2015/03/04
[ "https://wordpress.stackexchange.com/questions/180153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68565/" ]
I am trying to implement an archive for a custom post type: ``` http://mywebsite:8888/about-us/client-news/2015/03/ ``` The problem is that it keeps serving me a 404 page and I cannot work out what page template its failing to find. I have tried turning on debug and a number of other steps The registration: ``` function client_news() { $labels = array( 'name' => _x("Client News", "post type general name"), 'singular_name' => _x("Client News Item", "post type singular name"), 'menu_name' => 'Client News', 'add_new' => _x("Add New", "news item"), 'add_new_item' => __("Add New News Item"), 'edit_item' => __("Edit News Item"), 'new_item' => __("New News Item"), 'view_item' => __("View News Item"), 'search_items' => __("Search Client News"), 'not_found' => __("No Useful Items Found"), 'not_found_in_trash' => __("No Useful Items Found in Trash"), 'parent_item_colon' => '' ); // Register post type register_post_type('clientnews' , array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => 'news' ), 'supports' => array('title', 'editor', 'thumbnail') ) ); } add_action( 'init', 'client_news', 0 ); ``` Archive loop is as follows: ``` <ul class="news_archive"> <?php add_filter( 'get_archives_link', 'get_archives_clientnews_link', 10, 2 ); wp_get_archives( array( 'post_type' => 'clientnews', 'type' => 'monthly' ) ); remove_filter( 'get_archives_link', 'get_archives_clientnews_link', 10, 2 ); ?> </ul> ```
I have managed to resolve this by adding in a custom rewrite into the functions file: ``` // Add custom rewrite rules to handle things like years in custom post archives function add_rewrite_rules($aRules) { $aNewRules = array( 'news/([0-9]{4})/([0-9]{2})/page/?([0-9]{1,})/?$' => 'index.php?post_type=clientnews&year=$matches[1]&monthnum=$matches[2]&paged=$matches[3]', 'news/([0-9]{4})/([0-9]{2})/?$' => 'index.php?post_type=clientnews&year=$matches[1]&monthnum=$matches[2]', 'about-us/other-news/([0-9]{4})/([0-9]{2})/page/?([0-9]{1,})/?$' => 'index.php?post_type=othernews&year=$matches[1]&monthnum=$matches[2]&paged=$matches[3]', 'about-us/other-news/([0-9]{4})/([0-9]{2})/?$' => 'index.php?post_type=othernews&year=$matches[1]&monthnum=$matches[2]' ); $aRules = $aNewRules + $aRules; return $aRules; } // hook add_rewrite_rules function into rewrite_rules_array add_filter('rewrite_rules_array', 'add_rewrite_rules'); ``` Then in the archive page I changed the query to: ``` $aParts = explode( '/', $_SERVER['REQUEST_URI'] ); $iYear = get_query_var('year'); $iMonth = get_query_var('monthnum'); if( $iMonth <= 0 && $iYear > 0 ) { $iMonth = $aParts[ 4 ]; } $news = new WP_Query('showposts=6&post_type=othernews&paged='. $paged . '&year=' . $iYear . '&monthnum=' . $iMonth ); ```
180,221
<p>I am trying to create a Menu that shows a maximum of 5 items. If there are more items it should wrap them into another <code>&lt;ul&gt;</code> Element to create a dropdown.</p> <p>5 Items or less:</p> <p><img src="https://i.imgur.com/FGvn84z.png" alt="Dropdown"></p> <p>6 Items or more</p> <p><img src="https://i.imgur.com/Avxaqjt.png" alt="Dropdown"></p> <p>I know this kind of functionality could easily be created with a walker that counts the menu items and wraps if there are more then 5 the remaing into a seperate <code>&lt;ul&gt;</code>. But I dont know how to create this walker.</p> <p>The code that shows my menu at the moment is the following:</p> <pre><code>&lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'navigation', 'fallback_cb' =&gt; 'custom_menu', 'walker' =&gt;new Custom_Walker_Nav_Menu ) ); ?&gt; </code></pre> <p>I noticed that if the menu is not defined by the user and it uses the fallback function instead the walker has no effect. I need it to work in both cases.</p>
[ { "answer_id": 180248, "author": "mjakic", "author_id": 67333, "author_profile": "https://wordpress.stackexchange.com/users/67333", "pm_score": 3, "selected": false, "text": "<p>You can use <code>wp_nav_menu_items</code> filter. It accepts menu output and arguments which hold menu attributes, like menu slug, container, etc.</p>\n\n<pre><code>add_filter('wp_nav_menu_items', 'wpse_180221_nav_menu_items', 20, 2);\n\nfunction wpse_180221_nav_menu_items($items, $args) {\n if ($args-&gt;menu != 'my-menu-slug') {\n return $items;\n }\n\n // extract all &lt;li&gt;&lt;/li&gt; elements from menu output\n preg_match_all('/&lt;li[^&gt;]*&gt;.*?&lt;\\/li&gt;/iU', $items, $matches);\n\n // if menu has less the 5 items, just do nothing\n if (! isset($matches[0][5])) {\n return $items;\n }\n\n // add &lt;ul&gt; after 5th item (can be any number - can use e.g. site-wide variable)\n $matches[0][5] = '&lt;li class=\"menu-item menu-item-type-custom\"&gt;&amp;hellip;&lt;ul&gt;'\n . $matches[0][5];\n\n // $matches contain multidimensional array\n // first (and only) item is found matches array\n return implode('', $matches[0]) . '&lt;/ul&gt;&lt;/li&gt;';\n}\n</code></pre>\n" }, { "answer_id": 180258, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": false, "text": "<p>There even is a way to make this possible with CSS alone. This has some limitations, but I still thought it might be an interesting approach:</p>\n\n<h2>Limitations</h2>\n\n<ul>\n<li>You need to hardcode the width of the dropdown</li>\n<li>Browser-Support. You basically need <a href=\"http://caniuse.com/#feat=css-sel3\" rel=\"nofollow\">CSS3 selectors</a>. But everything from IE8 up should work, although I haven't tested this.</li>\n<li>This is more of a proof-of-concept. There are several drawbacks like only working if there are no sub-items.</li>\n</ul>\n\n<h2>Approach</h2>\n\n<p>Although I'm not really using \"Quantity Queries\" the creative usage of <code>:nth-child</code> and <code>~</code> I've read in the recent <a href=\"http://alistapart.com/article/quantity-queries-for-css\" rel=\"nofollow\">Quantity Queries for CSS</a> were what led me to this solution.</p>\n\n<p>The approach is basically this:</p>\n\n<ol>\n<li>Hide all items after the 4th</li>\n<li>Add <code>...</code> dots using a <code>before</code> pseudo-element.</li>\n<li>When hovering the dots (or any of the hidden elements) show the extra items aka the submenu.</li>\n</ol>\n\n<p>Here is the CSS code for a default WordPress menu markup. I've commented inline.</p>\n\n<pre><code>/* Optional: Center the navigation */\n.main-navigation {\n text-align: center;\n}\n\n.menu-main-menu-container {\n display: inline-block;\n}\n\n/* Float menu items */\n.nav-menu li {\n float:left;\n list-style-type: none;\n}\n\n/* Pull the 5th menu item to the left a bit so that there isn't too\n much space between item 4 and ... */\n.nav-menu li:nth-child(4) {\n margin-right: -60px;\n}\n\n/* Create a pseudo element for ... and force line break afterwards\n (Hint: Use a symbol font to improve styling) */\n.nav-menu li:nth-child(5):before {\n content: \"...\\A\";\n white-space: pre;\n}\n\n/* Give the first 4 items some padding and push them in front of the submenu */\n.nav-menu li:nth-child(-n+4) {\n padding-right: 15px;\n position: relative;\n z-index: 1;\n}\n\n/* Float dropdown-items to the right. Hardcode width of dropdown. */\n.nav-menu li:nth-child(n+5) {\n float:right;\n clear: right;\n width: 150px;\n}\n\n/* Float Links in dropdown to the right and hide by default */\n.nav-menu li:nth-child(n+5) a{\n display: none; \n float: right;\n clear: right;\n} \n\n/* When hovering the menu, show all menu items from the 5th on */\n.nav-menu:hover li:nth-child(n+5) a,\n.nav-menu:hover li:nth-child(n+5) ~ li a{\n display: inherit;\n}\n\n/* When hovering one of the first 4 items, hide all items after it \n so we do not activate the dropdown on the first 4 items */\n.nav-menu li:nth-child(-n+4):hover ~ li:nth-child(n+5) a{\n display: none;\n}\n</code></pre>\n\n<p>I've also created a jsfiddle to show it in action: <a href=\"http://jsfiddle.net/jg6pLfd1/\" rel=\"nofollow\">http://jsfiddle.net/jg6pLfd1/</a></p>\n\n<p>If you have any further questions how this works please leave a comment, I'd be happy to clarify the code further.</p>\n" }, { "answer_id": 180352, "author": "Snowball", "author_id": 68011, "author_profile": "https://wordpress.stackexchange.com/users/68011", "pm_score": 3, "selected": false, "text": "<p>Got a working function, but not sure if it is the best solution.</p>\n\n<p>I used a custom walker:</p>\n\n<pre><code>class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {\nfunction start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n /**\n * This counts the $menu_items and wraps if there are more then 5 items the\n * remaining items into an extra &lt;ul&gt;\n */\n global $menu_items;\n $menu_items = substr_count($output,'&lt;li');\n if ($menu_items == 4) {\n $output .= '&lt;li class=\"tooltip\"&gt;&lt;span&gt;...&lt;/span&gt;&lt;ul class=\"tooltip-menu\"&gt;';\n }\n\n $output .= $indent . '&lt;li' . $id . $class_names .'&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a'. $attributes .'&gt;';\n $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n\n }\n}\n</code></pre>\n\n<p>The function that shows the actual menu is the following:</p>\n\n<pre><code> &lt;?php\n wp_nav_menu( array( 'container' =&gt; false, 'theme_location' =&gt; 'navigation', 'fallback_cb' =&gt; 'custom_menu', 'walker' =&gt;new Custom_Walker_Nav_Menu ) );\n global $menu_items;\n // This adds the closing &lt;/li&gt; and &lt;/ul&gt; if there are more then 4 items in the menu\n if ($menu_items &gt; 4) {\n echo \"&lt;/li&gt;&lt;/ul&gt;\";\n }\n ?&gt;\n</code></pre>\n\n<p>I declared the global variable $menu_items and used it to show the closing <code>&lt;li&gt;</code> and <code>&lt;ul&gt;</code>-tags. Its probabbly possible to do that as well inside the custom walker, but I didn't found where and how.</p>\n\n<p><strong>Two problems:</strong>\n1. If there are just 5 Items in the Menu, it wraps the last item as well into an althought there is no need for it.</p>\n\n<ol start=\"2\">\n<li>It just works if the user has actually allocated a menu to the theme_location, the walker doesn't fire if wp_nav_menu is showing the fallback function</li>\n</ol>\n" }, { "answer_id": 180420, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": true, "text": "<p>Using a custom Walker, the <code>start_el()</code> method has access to <code>$depth</code> param: when it is <code>0</code> the elemnt is a top one, and we can use this info to maintain an internal counter.</p>\n\n<p>When the counter reach a limit, we can use <code>DOMDocument</code> to get from full HTML output just the last element added, wrap it in a submenu and add it again to HTML.</p>\n\n<hr>\n\n<h3>Edit</h3>\n\n<p>When the number of elements are exactly the number we required + 1, e.g. we required 5 elements be visible and menu has 6, it makes no sense to split the menu, because elements will be 6 either way.\nThe code was edited to address that.</p>\n\n<hr>\n\n<p>Here's the code:</p>\n\n<pre><code>class SplitMenuWalker extends Walker_Nav_Menu {\n\n private $split_at;\n private $button;\n private $count = 0;\n private $wrappedOutput;\n private $replaceTarget;\n private $wrapped = false;\n private $toSplit = false;\n\n public function __construct($split_at = 5, $button = '&lt;a href=\"#\"&gt;&amp;hellip;&lt;/a&gt;') {\n $this-&gt;split_at = $split_at;\n $this-&gt;button = $button;\n }\n\n public function walk($elements, $max_depth) {\n $args = array_slice(func_get_args(), 2);\n $output = parent::walk($elements, $max_depth, reset($args));\n return $this-&gt;toSplit ? $output.'&lt;/ul&gt;&lt;/li&gt;' : $output;\n }\n\n public function start_el(&amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n $this-&gt;count += $depth === 0 ? 1 : 0;\n parent::start_el($output, $item, $depth, $args, $id);\n if (($this-&gt;count === $this-&gt;split_at) &amp;&amp; ! $this-&gt;wrapped) {\n // split at number has been reached generate and store wrapped output\n $this-&gt;wrapped = true;\n $this-&gt;replaceTarget = $output;\n $this-&gt;wrappedOutput = $this-&gt;wrappedOutput($output);\n } elseif(($this-&gt;count === $this-&gt;split_at + 1) &amp;&amp; ! $this-&gt;toSplit) {\n // split at number has been exceeded, replace regular with wrapped output\n $this-&gt;toSplit = true;\n $output = str_replace($this-&gt;replaceTarget, $this-&gt;wrappedOutput, $output);\n }\n }\n\n private function wrappedOutput($output) {\n $dom = new DOMDocument;\n $dom-&gt;loadHTML($output.'&lt;/li&gt;');\n $lis = $dom-&gt;getElementsByTagName('li');\n $last = trim(substr($dom-&gt;saveHTML($lis-&gt;item($lis-&gt;length-1)), 0, -5));\n // remove last li\n $wrappedOutput = substr(trim($output), 0, -1 * strlen($last));\n $classes = array(\n 'menu-item',\n 'menu-item-type-custom',\n 'menu-item-object-custom',\n 'menu-item-has-children',\n 'menu-item-split-wrapper'\n );\n // add wrap li element\n $wrappedOutput .= '&lt;li class=\"'.implode(' ', $classes).'\"&gt;';\n // add the \"more\" link\n $wrappedOutput .= $this-&gt;button;\n // add the last item wrapped in a submenu and return\n return $wrappedOutput . '&lt;ul class=\"sub-menu\"&gt;'. $last;\n }\n}\n</code></pre>\n\n<p>The usage is pretty simple:</p>\n\n<pre><code>// by default make visible 5 elements\nwp_nav_menu(array('menu' =&gt; 'my_menu', 'walker' =&gt; new SplitMenuWalker()));\n\n// let's make visible 2 elements\nwp_nav_menu(array('menu' =&gt; 'another_menu', 'walker' =&gt; new SplitMenuWalker(2)));\n\n// customize the link to click/over to see wrapped items\nwp_nav_menu(array(\n 'menu' =&gt; 'another_menu',\n 'walker' =&gt; new SplitMenuWalker(5, '&lt;a href=\"#\"&gt;more...&lt;/a&gt;')\n));\n</code></pre>\n" } ]
2015/03/05
[ "https://wordpress.stackexchange.com/questions/180221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68011/" ]
I am trying to create a Menu that shows a maximum of 5 items. If there are more items it should wrap them into another `<ul>` Element to create a dropdown. 5 Items or less: ![Dropdown](https://i.imgur.com/FGvn84z.png) 6 Items or more ![Dropdown](https://i.imgur.com/Avxaqjt.png) I know this kind of functionality could easily be created with a walker that counts the menu items and wraps if there are more then 5 the remaing into a seperate `<ul>`. But I dont know how to create this walker. The code that shows my menu at the moment is the following: ``` <?php wp_nav_menu( array( 'theme_location' => 'navigation', 'fallback_cb' => 'custom_menu', 'walker' =>new Custom_Walker_Nav_Menu ) ); ?> ``` I noticed that if the menu is not defined by the user and it uses the fallback function instead the walker has no effect. I need it to work in both cases.
Using a custom Walker, the `start_el()` method has access to `$depth` param: when it is `0` the elemnt is a top one, and we can use this info to maintain an internal counter. When the counter reach a limit, we can use `DOMDocument` to get from full HTML output just the last element added, wrap it in a submenu and add it again to HTML. --- ### Edit When the number of elements are exactly the number we required + 1, e.g. we required 5 elements be visible and menu has 6, it makes no sense to split the menu, because elements will be 6 either way. The code was edited to address that. --- Here's the code: ``` class SplitMenuWalker extends Walker_Nav_Menu { private $split_at; private $button; private $count = 0; private $wrappedOutput; private $replaceTarget; private $wrapped = false; private $toSplit = false; public function __construct($split_at = 5, $button = '<a href="#">&hellip;</a>') { $this->split_at = $split_at; $this->button = $button; } public function walk($elements, $max_depth) { $args = array_slice(func_get_args(), 2); $output = parent::walk($elements, $max_depth, reset($args)); return $this->toSplit ? $output.'</ul></li>' : $output; } public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0 ) { $this->count += $depth === 0 ? 1 : 0; parent::start_el($output, $item, $depth, $args, $id); if (($this->count === $this->split_at) && ! $this->wrapped) { // split at number has been reached generate and store wrapped output $this->wrapped = true; $this->replaceTarget = $output; $this->wrappedOutput = $this->wrappedOutput($output); } elseif(($this->count === $this->split_at + 1) && ! $this->toSplit) { // split at number has been exceeded, replace regular with wrapped output $this->toSplit = true; $output = str_replace($this->replaceTarget, $this->wrappedOutput, $output); } } private function wrappedOutput($output) { $dom = new DOMDocument; $dom->loadHTML($output.'</li>'); $lis = $dom->getElementsByTagName('li'); $last = trim(substr($dom->saveHTML($lis->item($lis->length-1)), 0, -5)); // remove last li $wrappedOutput = substr(trim($output), 0, -1 * strlen($last)); $classes = array( 'menu-item', 'menu-item-type-custom', 'menu-item-object-custom', 'menu-item-has-children', 'menu-item-split-wrapper' ); // add wrap li element $wrappedOutput .= '<li class="'.implode(' ', $classes).'">'; // add the "more" link $wrappedOutput .= $this->button; // add the last item wrapped in a submenu and return return $wrappedOutput . '<ul class="sub-menu">'. $last; } } ``` The usage is pretty simple: ``` // by default make visible 5 elements wp_nav_menu(array('menu' => 'my_menu', 'walker' => new SplitMenuWalker())); // let's make visible 2 elements wp_nav_menu(array('menu' => 'another_menu', 'walker' => new SplitMenuWalker(2))); // customize the link to click/over to see wrapped items wp_nav_menu(array( 'menu' => 'another_menu', 'walker' => new SplitMenuWalker(5, '<a href="#">more...</a>') )); ```
180,227
<p>So, I have this post title that has a certain length (say 15 words).</p> <p>When the browser width is reduced, the overflown words are placed to a next line by pushing everything down.</p> <p>However, is there a way to replace the overflown words with "..." so that there is no pushing down on the other contents?</p> <p>Thanks!</p>
[ { "answer_id": 180248, "author": "mjakic", "author_id": 67333, "author_profile": "https://wordpress.stackexchange.com/users/67333", "pm_score": 3, "selected": false, "text": "<p>You can use <code>wp_nav_menu_items</code> filter. It accepts menu output and arguments which hold menu attributes, like menu slug, container, etc.</p>\n\n<pre><code>add_filter('wp_nav_menu_items', 'wpse_180221_nav_menu_items', 20, 2);\n\nfunction wpse_180221_nav_menu_items($items, $args) {\n if ($args-&gt;menu != 'my-menu-slug') {\n return $items;\n }\n\n // extract all &lt;li&gt;&lt;/li&gt; elements from menu output\n preg_match_all('/&lt;li[^&gt;]*&gt;.*?&lt;\\/li&gt;/iU', $items, $matches);\n\n // if menu has less the 5 items, just do nothing\n if (! isset($matches[0][5])) {\n return $items;\n }\n\n // add &lt;ul&gt; after 5th item (can be any number - can use e.g. site-wide variable)\n $matches[0][5] = '&lt;li class=\"menu-item menu-item-type-custom\"&gt;&amp;hellip;&lt;ul&gt;'\n . $matches[0][5];\n\n // $matches contain multidimensional array\n // first (and only) item is found matches array\n return implode('', $matches[0]) . '&lt;/ul&gt;&lt;/li&gt;';\n}\n</code></pre>\n" }, { "answer_id": 180258, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": false, "text": "<p>There even is a way to make this possible with CSS alone. This has some limitations, but I still thought it might be an interesting approach:</p>\n\n<h2>Limitations</h2>\n\n<ul>\n<li>You need to hardcode the width of the dropdown</li>\n<li>Browser-Support. You basically need <a href=\"http://caniuse.com/#feat=css-sel3\" rel=\"nofollow\">CSS3 selectors</a>. But everything from IE8 up should work, although I haven't tested this.</li>\n<li>This is more of a proof-of-concept. There are several drawbacks like only working if there are no sub-items.</li>\n</ul>\n\n<h2>Approach</h2>\n\n<p>Although I'm not really using \"Quantity Queries\" the creative usage of <code>:nth-child</code> and <code>~</code> I've read in the recent <a href=\"http://alistapart.com/article/quantity-queries-for-css\" rel=\"nofollow\">Quantity Queries for CSS</a> were what led me to this solution.</p>\n\n<p>The approach is basically this:</p>\n\n<ol>\n<li>Hide all items after the 4th</li>\n<li>Add <code>...</code> dots using a <code>before</code> pseudo-element.</li>\n<li>When hovering the dots (or any of the hidden elements) show the extra items aka the submenu.</li>\n</ol>\n\n<p>Here is the CSS code for a default WordPress menu markup. I've commented inline.</p>\n\n<pre><code>/* Optional: Center the navigation */\n.main-navigation {\n text-align: center;\n}\n\n.menu-main-menu-container {\n display: inline-block;\n}\n\n/* Float menu items */\n.nav-menu li {\n float:left;\n list-style-type: none;\n}\n\n/* Pull the 5th menu item to the left a bit so that there isn't too\n much space between item 4 and ... */\n.nav-menu li:nth-child(4) {\n margin-right: -60px;\n}\n\n/* Create a pseudo element for ... and force line break afterwards\n (Hint: Use a symbol font to improve styling) */\n.nav-menu li:nth-child(5):before {\n content: \"...\\A\";\n white-space: pre;\n}\n\n/* Give the first 4 items some padding and push them in front of the submenu */\n.nav-menu li:nth-child(-n+4) {\n padding-right: 15px;\n position: relative;\n z-index: 1;\n}\n\n/* Float dropdown-items to the right. Hardcode width of dropdown. */\n.nav-menu li:nth-child(n+5) {\n float:right;\n clear: right;\n width: 150px;\n}\n\n/* Float Links in dropdown to the right and hide by default */\n.nav-menu li:nth-child(n+5) a{\n display: none; \n float: right;\n clear: right;\n} \n\n/* When hovering the menu, show all menu items from the 5th on */\n.nav-menu:hover li:nth-child(n+5) a,\n.nav-menu:hover li:nth-child(n+5) ~ li a{\n display: inherit;\n}\n\n/* When hovering one of the first 4 items, hide all items after it \n so we do not activate the dropdown on the first 4 items */\n.nav-menu li:nth-child(-n+4):hover ~ li:nth-child(n+5) a{\n display: none;\n}\n</code></pre>\n\n<p>I've also created a jsfiddle to show it in action: <a href=\"http://jsfiddle.net/jg6pLfd1/\" rel=\"nofollow\">http://jsfiddle.net/jg6pLfd1/</a></p>\n\n<p>If you have any further questions how this works please leave a comment, I'd be happy to clarify the code further.</p>\n" }, { "answer_id": 180352, "author": "Snowball", "author_id": 68011, "author_profile": "https://wordpress.stackexchange.com/users/68011", "pm_score": 3, "selected": false, "text": "<p>Got a working function, but not sure if it is the best solution.</p>\n\n<p>I used a custom walker:</p>\n\n<pre><code>class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {\nfunction start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n /**\n * This counts the $menu_items and wraps if there are more then 5 items the\n * remaining items into an extra &lt;ul&gt;\n */\n global $menu_items;\n $menu_items = substr_count($output,'&lt;li');\n if ($menu_items == 4) {\n $output .= '&lt;li class=\"tooltip\"&gt;&lt;span&gt;...&lt;/span&gt;&lt;ul class=\"tooltip-menu\"&gt;';\n }\n\n $output .= $indent . '&lt;li' . $id . $class_names .'&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a'. $attributes .'&gt;';\n $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n\n }\n}\n</code></pre>\n\n<p>The function that shows the actual menu is the following:</p>\n\n<pre><code> &lt;?php\n wp_nav_menu( array( 'container' =&gt; false, 'theme_location' =&gt; 'navigation', 'fallback_cb' =&gt; 'custom_menu', 'walker' =&gt;new Custom_Walker_Nav_Menu ) );\n global $menu_items;\n // This adds the closing &lt;/li&gt; and &lt;/ul&gt; if there are more then 4 items in the menu\n if ($menu_items &gt; 4) {\n echo \"&lt;/li&gt;&lt;/ul&gt;\";\n }\n ?&gt;\n</code></pre>\n\n<p>I declared the global variable $menu_items and used it to show the closing <code>&lt;li&gt;</code> and <code>&lt;ul&gt;</code>-tags. Its probabbly possible to do that as well inside the custom walker, but I didn't found where and how.</p>\n\n<p><strong>Two problems:</strong>\n1. If there are just 5 Items in the Menu, it wraps the last item as well into an althought there is no need for it.</p>\n\n<ol start=\"2\">\n<li>It just works if the user has actually allocated a menu to the theme_location, the walker doesn't fire if wp_nav_menu is showing the fallback function</li>\n</ol>\n" }, { "answer_id": 180420, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": true, "text": "<p>Using a custom Walker, the <code>start_el()</code> method has access to <code>$depth</code> param: when it is <code>0</code> the elemnt is a top one, and we can use this info to maintain an internal counter.</p>\n\n<p>When the counter reach a limit, we can use <code>DOMDocument</code> to get from full HTML output just the last element added, wrap it in a submenu and add it again to HTML.</p>\n\n<hr>\n\n<h3>Edit</h3>\n\n<p>When the number of elements are exactly the number we required + 1, e.g. we required 5 elements be visible and menu has 6, it makes no sense to split the menu, because elements will be 6 either way.\nThe code was edited to address that.</p>\n\n<hr>\n\n<p>Here's the code:</p>\n\n<pre><code>class SplitMenuWalker extends Walker_Nav_Menu {\n\n private $split_at;\n private $button;\n private $count = 0;\n private $wrappedOutput;\n private $replaceTarget;\n private $wrapped = false;\n private $toSplit = false;\n\n public function __construct($split_at = 5, $button = '&lt;a href=\"#\"&gt;&amp;hellip;&lt;/a&gt;') {\n $this-&gt;split_at = $split_at;\n $this-&gt;button = $button;\n }\n\n public function walk($elements, $max_depth) {\n $args = array_slice(func_get_args(), 2);\n $output = parent::walk($elements, $max_depth, reset($args));\n return $this-&gt;toSplit ? $output.'&lt;/ul&gt;&lt;/li&gt;' : $output;\n }\n\n public function start_el(&amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n $this-&gt;count += $depth === 0 ? 1 : 0;\n parent::start_el($output, $item, $depth, $args, $id);\n if (($this-&gt;count === $this-&gt;split_at) &amp;&amp; ! $this-&gt;wrapped) {\n // split at number has been reached generate and store wrapped output\n $this-&gt;wrapped = true;\n $this-&gt;replaceTarget = $output;\n $this-&gt;wrappedOutput = $this-&gt;wrappedOutput($output);\n } elseif(($this-&gt;count === $this-&gt;split_at + 1) &amp;&amp; ! $this-&gt;toSplit) {\n // split at number has been exceeded, replace regular with wrapped output\n $this-&gt;toSplit = true;\n $output = str_replace($this-&gt;replaceTarget, $this-&gt;wrappedOutput, $output);\n }\n }\n\n private function wrappedOutput($output) {\n $dom = new DOMDocument;\n $dom-&gt;loadHTML($output.'&lt;/li&gt;');\n $lis = $dom-&gt;getElementsByTagName('li');\n $last = trim(substr($dom-&gt;saveHTML($lis-&gt;item($lis-&gt;length-1)), 0, -5));\n // remove last li\n $wrappedOutput = substr(trim($output), 0, -1 * strlen($last));\n $classes = array(\n 'menu-item',\n 'menu-item-type-custom',\n 'menu-item-object-custom',\n 'menu-item-has-children',\n 'menu-item-split-wrapper'\n );\n // add wrap li element\n $wrappedOutput .= '&lt;li class=\"'.implode(' ', $classes).'\"&gt;';\n // add the \"more\" link\n $wrappedOutput .= $this-&gt;button;\n // add the last item wrapped in a submenu and return\n return $wrappedOutput . '&lt;ul class=\"sub-menu\"&gt;'. $last;\n }\n}\n</code></pre>\n\n<p>The usage is pretty simple:</p>\n\n<pre><code>// by default make visible 5 elements\nwp_nav_menu(array('menu' =&gt; 'my_menu', 'walker' =&gt; new SplitMenuWalker()));\n\n// let's make visible 2 elements\nwp_nav_menu(array('menu' =&gt; 'another_menu', 'walker' =&gt; new SplitMenuWalker(2)));\n\n// customize the link to click/over to see wrapped items\nwp_nav_menu(array(\n 'menu' =&gt; 'another_menu',\n 'walker' =&gt; new SplitMenuWalker(5, '&lt;a href=\"#\"&gt;more...&lt;/a&gt;')\n));\n</code></pre>\n" } ]
2015/03/05
[ "https://wordpress.stackexchange.com/questions/180227", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So, I have this post title that has a certain length (say 15 words). When the browser width is reduced, the overflown words are placed to a next line by pushing everything down. However, is there a way to replace the overflown words with "..." so that there is no pushing down on the other contents? Thanks!
Using a custom Walker, the `start_el()` method has access to `$depth` param: when it is `0` the elemnt is a top one, and we can use this info to maintain an internal counter. When the counter reach a limit, we can use `DOMDocument` to get from full HTML output just the last element added, wrap it in a submenu and add it again to HTML. --- ### Edit When the number of elements are exactly the number we required + 1, e.g. we required 5 elements be visible and menu has 6, it makes no sense to split the menu, because elements will be 6 either way. The code was edited to address that. --- Here's the code: ``` class SplitMenuWalker extends Walker_Nav_Menu { private $split_at; private $button; private $count = 0; private $wrappedOutput; private $replaceTarget; private $wrapped = false; private $toSplit = false; public function __construct($split_at = 5, $button = '<a href="#">&hellip;</a>') { $this->split_at = $split_at; $this->button = $button; } public function walk($elements, $max_depth) { $args = array_slice(func_get_args(), 2); $output = parent::walk($elements, $max_depth, reset($args)); return $this->toSplit ? $output.'</ul></li>' : $output; } public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0 ) { $this->count += $depth === 0 ? 1 : 0; parent::start_el($output, $item, $depth, $args, $id); if (($this->count === $this->split_at) && ! $this->wrapped) { // split at number has been reached generate and store wrapped output $this->wrapped = true; $this->replaceTarget = $output; $this->wrappedOutput = $this->wrappedOutput($output); } elseif(($this->count === $this->split_at + 1) && ! $this->toSplit) { // split at number has been exceeded, replace regular with wrapped output $this->toSplit = true; $output = str_replace($this->replaceTarget, $this->wrappedOutput, $output); } } private function wrappedOutput($output) { $dom = new DOMDocument; $dom->loadHTML($output.'</li>'); $lis = $dom->getElementsByTagName('li'); $last = trim(substr($dom->saveHTML($lis->item($lis->length-1)), 0, -5)); // remove last li $wrappedOutput = substr(trim($output), 0, -1 * strlen($last)); $classes = array( 'menu-item', 'menu-item-type-custom', 'menu-item-object-custom', 'menu-item-has-children', 'menu-item-split-wrapper' ); // add wrap li element $wrappedOutput .= '<li class="'.implode(' ', $classes).'">'; // add the "more" link $wrappedOutput .= $this->button; // add the last item wrapped in a submenu and return return $wrappedOutput . '<ul class="sub-menu">'. $last; } } ``` The usage is pretty simple: ``` // by default make visible 5 elements wp_nav_menu(array('menu' => 'my_menu', 'walker' => new SplitMenuWalker())); // let's make visible 2 elements wp_nav_menu(array('menu' => 'another_menu', 'walker' => new SplitMenuWalker(2))); // customize the link to click/over to see wrapped items wp_nav_menu(array( 'menu' => 'another_menu', 'walker' => new SplitMenuWalker(5, '<a href="#">more...</a>') )); ```
180,240
<p>I am wondering if this could be done if i want something like this. Look at my code please.</p> <p>Here the code goes:</p> <pre><code>&lt;?php _e('Search result for','NCC'); ?&gt; &lt;?php /* Search Count */ $allsearch = &amp;new WP_Query("s=$s&amp;showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch-&gt;post_count; _e(''); _e('"&lt;span&gt;'); echo $key; _e('&lt;/span&gt;"'); _e('&lt;span class="resultsFound"&gt;( We found '); echo $count . ' '; _e('companies )&lt;/span&gt;'); wp_reset_query(); ?&gt; </code></pre> <p>The outcome of this code will be:</p> <pre><code>( We found 1 companies ) </code></pre> <p>Is it possible to make it work like the result saying "company" when there is 0 or 1 result found and saying "companies" when there are more 2 or more results found when we using the wp search box?</p> <p>Example:</p> <pre><code>(1 company found) or (2 companies found) </code></pre> <p>Any suggestion? Is it possible with wordpress?</p>
[ { "answer_id": 180242, "author": "tutankhamun", "author_id": 68544, "author_profile": "https://wordpress.stackexchange.com/users/68544", "pm_score": 0, "selected": false, "text": "<p>You may use <code>_n</code> function instead of <code>_e</code>.</p>\n\n<p>Read this: <a href=\"http://codex.wordpress.org/Function_Reference/_n\" rel=\"nofollow\"><code>_n</code></a></p>\n" }, { "answer_id": 180244, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p><code>$found_posts</code> holds the amount of posts found by a certain query. You can use this logic to display your links</p>\n\n<p>Example:</p>\n\n<pre><code>if ( $allsearch-&gt;found_posts &lt;= 1 ) {\n //Dispaly company\n} else {\n // Disply companies\n}\n</code></pre>\n\n<p>Just a note on grammar, it should be <code>0 companies</code> <code>1 company</code> and <code>x amount of companies</code> after that</p>\n\n<h2><strong>EDIT</strong></h2>\n\n<p>From the edit I have done to your question, I have the following: To be honest, your code is a bit of a mess, but nothing that cannot be fixed though :-). Lets take a quick run down</p>\n\n<ul>\n<li><p><code>showposts</code> is depreciated in favor of <code>posts_per_page</code></p></li>\n<li><p><a href=\"http://codex.wordpress.org/Function_Reference/wp_specialchars\" rel=\"nofollow\"><code>wp_specialchars</code></a> has been depreciated since v2.8.0. You should be using <a href=\"http://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow\"><code>esc_html</code></a>. But to be honest, I don't know if it is appropriate here.</p></li>\n<li><p>You should not localize HTML tags, just literal text should be localized. Exclude HTML tags from strings to be localized and make use of placeholders</p></li>\n<li><p><code>wp_reset_query()</code> should be used with <code>query_posts</code> which you should never ever use. You should be using <code>wp_reset_postdata()</code> with <code>WP_Query</code>. In this case it is not necessary as you are not setting up postdata or changing the global <code>$post</code> variable</p></li>\n<li><p>I'm not very sure if you really need to localize the value of <code>$key</code></p></li>\n</ul>\n\n<p>As already stated in the other answer, you can make use of <code>_n()</code> to localize strings with single and plural meaning. As I have already stated, the correct grammar and use is</p>\n\n<ul>\n<li><code>0 companies</code> <code>1 company</code> and <code>x amount of companies</code></li>\n</ul>\n\n<p>Your issue is in this line</p>\n\n<pre><code>_e('&lt;span class=\"resultsFound\"&gt;( We found '); echo $count . ' '; _e('companies )&lt;/span&gt;'); \n</code></pre>\n\n<p>We can rewrite it to something like this</p>\n\n<pre><code>$text = '&lt;span class=\"resultsFound\"&gt;';\n$text .= sprintf( _n( 'We found %d company', 'We found %d companies', $count ), $count );\n$text .= '&lt;/span&gt;'; \necho $text;\n</code></pre>\n\n<p>If you really need to display <code>0 company</code>, you can use</p>\n\n<pre><code>$text = '&lt;span class=\"resultsFound\"&gt;';\nif ( $allsearch-&gt;found_posts &lt;= 1 ) {\n $text .= sprintf(__( 'We found %d company' ), $count );\n} else {\n $text .= sprintf(__( 'We found %d companies' ), $count );\n} \n$text .= '&lt;/span&gt;'; \necho $text;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$text = '&lt;span class=\"resultsFound\"&gt;';\nif ( $allsearch-&gt;post_count &lt;= 1 ) {\n $text .= sprintf(__( 'We found %d company' ), $count );\n} else {\n $text .= sprintf(__( 'We found %d companies' ), $count );\n} \n$text .= '&lt;/span&gt;'; \necho $text;\n</code></pre>\n" } ]
2015/03/05
[ "https://wordpress.stackexchange.com/questions/180240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23036/" ]
I am wondering if this could be done if i want something like this. Look at my code please. Here the code goes: ``` <?php _e('Search result for','NCC'); ?> <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('"<span>'); echo $key; _e('</span>"'); _e('<span class="resultsFound">( We found '); echo $count . ' '; _e('companies )</span>'); wp_reset_query(); ?> ``` The outcome of this code will be: ``` ( We found 1 companies ) ``` Is it possible to make it work like the result saying "company" when there is 0 or 1 result found and saying "companies" when there are more 2 or more results found when we using the wp search box? Example: ``` (1 company found) or (2 companies found) ``` Any suggestion? Is it possible with wordpress?
`$found_posts` holds the amount of posts found by a certain query. You can use this logic to display your links Example: ``` if ( $allsearch->found_posts <= 1 ) { //Dispaly company } else { // Disply companies } ``` Just a note on grammar, it should be `0 companies` `1 company` and `x amount of companies` after that **EDIT** -------- From the edit I have done to your question, I have the following: To be honest, your code is a bit of a mess, but nothing that cannot be fixed though :-). Lets take a quick run down * `showposts` is depreciated in favor of `posts_per_page` * [`wp_specialchars`](http://codex.wordpress.org/Function_Reference/wp_specialchars) has been depreciated since v2.8.0. You should be using [`esc_html`](http://codex.wordpress.org/Function_Reference/esc_html). But to be honest, I don't know if it is appropriate here. * You should not localize HTML tags, just literal text should be localized. Exclude HTML tags from strings to be localized and make use of placeholders * `wp_reset_query()` should be used with `query_posts` which you should never ever use. You should be using `wp_reset_postdata()` with `WP_Query`. In this case it is not necessary as you are not setting up postdata or changing the global `$post` variable * I'm not very sure if you really need to localize the value of `$key` As already stated in the other answer, you can make use of `_n()` to localize strings with single and plural meaning. As I have already stated, the correct grammar and use is * `0 companies` `1 company` and `x amount of companies` Your issue is in this line ``` _e('<span class="resultsFound">( We found '); echo $count . ' '; _e('companies )</span>'); ``` We can rewrite it to something like this ``` $text = '<span class="resultsFound">'; $text .= sprintf( _n( 'We found %d company', 'We found %d companies', $count ), $count ); $text .= '</span>'; echo $text; ``` If you really need to display `0 company`, you can use ``` $text = '<span class="resultsFound">'; if ( $allsearch->found_posts <= 1 ) { $text .= sprintf(__( 'We found %d company' ), $count ); } else { $text .= sprintf(__( 'We found %d companies' ), $count ); } $text .= '</span>'; echo $text; ``` or ``` $text = '<span class="resultsFound">'; if ( $allsearch->post_count <= 1 ) { $text .= sprintf(__( 'We found %d company' ), $count ); } else { $text .= sprintf(__( 'We found %d companies' ), $count ); } $text .= '</span>'; echo $text; ```
180,295
<p>I'm using the <code>avatar_defaults</code> filter hook to filter the default avatar list. For example:</p> <pre><code>function my_avatar_defaults( $avatar_defaults ) { $avatar_defaults['http://example.com/foo.png'] = __( 'Foo' ); return $avatar_defaults; } add_filter( 'avatar_defaults', 'my_avatar_defaults' ); </code></pre> <p>This works because if I visit Settings > Discussion and then scroll down, I can see Foo has been added as a default avatar option. See the following screenshot for an example:</p> <p><img src="https://i.stack.imgur.com/QoDDB.png" alt="Default avatar list of options"></p> <p>The problem is the <code>src</code> attribute of the image displayed next to Foo. It seems to be making a call to Gravatar. Here's an example of the source code I'm getting for the image next to Foo:</p> <pre><code>&lt;img src="http://0.gravatar.com/avatar/efaeb0e0be9922051a1c4ccce766a141?s=32&amp;d=http%3A%2F%2Fexample.com%2Ffoo.png%3Fs%3D32&amp;r=G&amp;forcedefault=1" /&gt; </code></pre> <p>How can I ensure the <code>src</code> attribute points to my image URL instead of the Gravatar URL (which seems to have my image's URL inside it)?</p>
[ { "answer_id": 180296, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 1, "selected": true, "text": "<p>You are doing it correctly.</p>\n\n<p>The call to gravatar.com passes the location of your custom image so that WP can load it. Take a look at the query string in the src, you'll see your image location. That's how it works.</p>\n" }, { "answer_id": 180317, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 1, "selected": false, "text": "<p>Two notes: </p>\n\n<ol>\n<li><a href=\"https://github.com/WordPress/WordPress/blob/4.0/wp-includes/pluggable.php#L2093\" rel=\"nofollow\"><code>get_avatar()</code></a> is a \"pluggable\" function. That means, that you can write a plugin to hold a new function named <code>get_avatar()</code>, which then will overwrite the original function used by WP.</li>\n<li><p><code>get_avatar()</code> also has a filter</p>\n\n<pre><code>return apply_filters( 'get_avatar', $avatar, $id_or_email, $size, $default, $alt );\n</code></pre>\n\n<p>that you can use to change the return value:</p>\n\n<pre><code>add_filter( 'get_avatar', function( $html, $id, $size, $default, $alt )\n{\n // apply some changes here\n return $html;\n}, 10, 5 );\n</code></pre>\n\n<p>and that means that you can simply change the <em>output</em> as well and remove the <code>src</code> call to \"Gravatar\" so that it doesn't happen.</p></li>\n</ol>\n" } ]
2015/03/05
[ "https://wordpress.stackexchange.com/questions/180295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
I'm using the `avatar_defaults` filter hook to filter the default avatar list. For example: ``` function my_avatar_defaults( $avatar_defaults ) { $avatar_defaults['http://example.com/foo.png'] = __( 'Foo' ); return $avatar_defaults; } add_filter( 'avatar_defaults', 'my_avatar_defaults' ); ``` This works because if I visit Settings > Discussion and then scroll down, I can see Foo has been added as a default avatar option. See the following screenshot for an example: ![Default avatar list of options](https://i.stack.imgur.com/QoDDB.png) The problem is the `src` attribute of the image displayed next to Foo. It seems to be making a call to Gravatar. Here's an example of the source code I'm getting for the image next to Foo: ``` <img src="http://0.gravatar.com/avatar/efaeb0e0be9922051a1c4ccce766a141?s=32&d=http%3A%2F%2Fexample.com%2Ffoo.png%3Fs%3D32&r=G&forcedefault=1" /> ``` How can I ensure the `src` attribute points to my image URL instead of the Gravatar URL (which seems to have my image's URL inside it)?
You are doing it correctly. The call to gravatar.com passes the location of your custom image so that WP can load it. Take a look at the query string in the src, you'll see your image location. That's how it works.
180,297
<p>In our <code>archive.php</code> we show all the items which match our selected category. This works absolutely fine.</p> <p>Then we improved it by adding (just before the loop) a sort and upping the posts per page from the default 10, like so:</p> <pre><code>$posts = query_posts($query_string . '&amp;orderby=title&amp;order=asc&amp;posts_per_page=99'); </code></pre> <p>This works even better.</p> <p>Now, however we want to sort by more than one field, say <code>menu_order</code> then <code>title</code>. I don't see a way to do this using this query_posts / querystring syntax we have in place. Code samples all involve firing up a new WP_Query, losing track of the query_string. What's the solution?</p>
[ { "answer_id": 180370, "author": "mjakic", "author_id": 67333, "author_profile": "https://wordpress.stackexchange.com/users/67333", "pm_score": 0, "selected": false, "text": "<p>There is ability to sort by more than one column. See <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow\">here</a>.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 99,\n 'orderby' =&gt; 'menu_order title',\n 'order' =&gt; 'ASC',\n);\n\n$query = new WP_Query( $args );\n// do your stuff here...\n\nwp_reset_postdata();\n</code></pre>\n\n<p>Check out <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Standard_Loop\" rel=\"nofollow\">standard loop</a> and why you should use <code>wp_reset_postdata</code>.</p>\n" }, { "answer_id": 180386, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>If you're altering the main query, always use <code>pre_get_posts</code> to alter query parameters <em>before</em> the query is run and before the template is loaded. This will be the most efficient and will not break pagination. As of v4, <code>orderby</code> accepts an array of arguments, which gives you the ability to have different <code>order</code> for each if necessary:</p>\n\n<pre><code>function my_get_posts( $query ){\n if( !is_admin() &amp;&amp; $query-&gt;is_category() &amp;&amp; $query-&gt;is_main_query() ){\n $query-&gt;set( 'posts_per_page', -1 ); // show all posts\n $query-&gt;set( 'orderby', array('menu_order' =&gt; 'ASC', 'title' =&gt; 'ASC') );\n }\n}\nadd_action( 'pre_get_posts', 'my_get_posts' );\n</code></pre>\n" } ]
2015/03/05
[ "https://wordpress.stackexchange.com/questions/180297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/875/" ]
In our `archive.php` we show all the items which match our selected category. This works absolutely fine. Then we improved it by adding (just before the loop) a sort and upping the posts per page from the default 10, like so: ``` $posts = query_posts($query_string . '&orderby=title&order=asc&posts_per_page=99'); ``` This works even better. Now, however we want to sort by more than one field, say `menu_order` then `title`. I don't see a way to do this using this query\_posts / querystring syntax we have in place. Code samples all involve firing up a new WP\_Query, losing track of the query\_string. What's the solution?
If you're altering the main query, always use `pre_get_posts` to alter query parameters *before* the query is run and before the template is loaded. This will be the most efficient and will not break pagination. As of v4, `orderby` accepts an array of arguments, which gives you the ability to have different `order` for each if necessary: ``` function my_get_posts( $query ){ if( !is_admin() && $query->is_category() && $query->is_main_query() ){ $query->set( 'posts_per_page', -1 ); // show all posts $query->set( 'orderby', array('menu_order' => 'ASC', 'title' => 'ASC') ); } } add_action( 'pre_get_posts', 'my_get_posts' ); ```
180,347
<p>I've been trying to integrate the <a href="http://owlgraphic.com/owlcarousel/#how-to" rel="nofollow noreferrer">owl.carousel</a> into my theme but can't get it to work. The instructions on the page are not for WordPress so I need help with how to properly enqueue the required files and calling (initializing) the carousel.</p> <p>I have added the following files to my themes directory located at <strong>MyTheme/inc/owl/</strong></p> <ul> <li>AjaxLoader.gif</li> <li>grabbing.png</li> <li>owl.carousel.css</li> <li>owl.carousel.js</li> <li>owl.carousel.min.js</li> <li>owl.carouselinit.js <em>-&gt; This is the &quot;call the Owl initializer function&quot;</em></li> <li>owl.theme.css</li> <li>owl.transitions.css</li> </ul> <p>In my functions.php file I enqueue the required files:</p> <pre><code>/*------------------------------------------------------------------------------- Add Owl Carousel -------------------------------------------------------------------------------*/ // Enqueue Scripts/Styles for our owl.carousel.2 function agencyclix_add_owlcarousel() { wp_enqueue_script ( 'jquery' ); wp_enqueue_script( 'owlcarousel', get_template_directory_uri() . '/inc/owl/owl.carousel.js', array( 'jquery' ), false, true ); wp_enqueue_script( 'owlcarousel', get_template_directory_uri() . '/inc/owl/owl.carousel.min.js', array( 'jquery' ), false, true ); wp_enqueue_script( 'owl-carousel', get_template_directory_uri() . '/inc/owl/owl.carousel-init.js', array( 'jquery' ), false, true ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.carousel.css' ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.theme.css' ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.transitions.css' ); } add_action( 'wp_enqueue_scripts', 'agencyclix_add_owlcarousel' ); </code></pre> <p>In the file &quot;owl.carouselinit.js&quot; I simply added the initializer function listed at the website which is:</p> <pre><code>$(document).ready(function(){ $('.owl-carousel').owlCarousel(); }); </code></pre> <p>Also I have looked at some plugins that use owl carousel and it looks like they are only using (enqueue) 3 files to use the owl carousel.</p> <p>Thanks in advanced</p>
[ { "answer_id": 219898, "author": "steamfunk", "author_id": 67512, "author_profile": "https://wordpress.stackexchange.com/users/67512", "pm_score": -1, "selected": false, "text": "<p>you do not have to enqueue both the owl.carousel.js and the owl.carousel.min.js just the min will do. also wordpress requires you to put any jquery into a non conflict wrapper. this would go into the file owl.carousel-init.js since that is the one you have enqueued. from your example you have not enqueued the file \"owl.carouselinit.js\". please look below to see how the owl init code will look in a non conflict wrapper:</p>\n\n<pre><code>jQuery(document).ready(function ($) {\n\n $(\"#custom-carousel\").owlCarousel({\n\n navigation: true, // Show next and prev buttons\n\n\n navigationText: [\n \"&lt;i class='fa fa-chevron-left icon-white'&gt;&lt;/i&gt;\",\n \"&lt;i class='fa fa-chevron-right icon-white'&gt;&lt;/i&gt;\"\n ],\n\n\n\n // pagination : false,\n // paginationNumbers: false,\n\n slideSpeed: 300,\n paginationSpeed: 400,\n\n items: 3,\n itemsCustom: false,\n itemsDesktop: [1199, 3],\n itemsDesktopSmall: [980, 3],\n itemsTablet: [768, 3],\n itemsTabletSmall: true,\n itemsMobile: [415, 2],\n singleItem: false,\n itemsScaleUp: false,\n\n\n\n });\n });\n</code></pre>\n\n<p>as you can see, owl carousel requires the id of the div and not the class. this is a class .owl-carousel and this would be an id #owl-carousel. From what i understand owl carousel requires you to use a custom id name like #custom-carousel which can be found in the code above. Hope that helps CHEERS!</p>\n" }, { "answer_id": 245205, "author": "Dan Fletcher", "author_id": 106387, "author_profile": "https://wordpress.stackexchange.com/users/106387", "pm_score": 0, "selected": false, "text": "<p>I don't claim to be a WP expert (nor do I care to be), but I had the same issue trying to get Owl Carousel to work on a wordpress site for a client, and I have an ugly solution.</p>\n\n<p>First of all as steamfunk pointed out, WordPress requires all jQuery to use <code>jQuery</code> rather than <code>$</code>. </p>\n\n<p>My initialization would look something like this:</p>\n\n<pre><code>jQuery(function() {\n jQuery('.owl-carousel').owlCarousel()\n})\n</code></pre>\n\n<p>I also was having issues figuring out how to enqueue my init script properly, so I decided to just put the script directly in the template I needed the carousel in.</p>\n\n<p>You can still keep it in the footer, and just echo the script conditionally:</p>\n\n<pre><code>&lt;?php if(is_page('name_of_page')): ?&gt;\n &lt;script&gt;\n // Your init stuff\n &lt;/script&gt;\n&lt;?php endif ?&gt; \n</code></pre>\n\n<p>Owl Carousel is the only plugin I've had issues doing things the \"Wordpress way\" so I guess it could be an issue with Owl Carousel. I don't know - again, not an expert.</p>\n\n<p>However, my solution may not be elegant, but it worked for my situation and I couldn't find a good answer for this question, which is why I'm sharing this here.</p>\n" }, { "answer_id": 245207, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 2, "selected": false, "text": "<p>You're reusing handles for the script and the styles. These need to be unique values (see <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">WP Codex Reference</a>)</p>\n\n<p>It should look something like this:</p>\n\n<pre><code>wp_enqueue_script( 'owlcarousel', get_template_directory_uri() . '/inc/owl/owl.carousel.min.js', array( 'jquery' ), false, true );\nwp_enqueue_script( 'owlcarousel-init', get_template_directory_uri() . '/inc/owl/owl.carousel-init.js', array( 'jquery' ), false, true );\nwp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.carousel.css' );\nwp_enqueue_style( 'owlcarousel-theme', get_template_directory_uri() . '/inc/owl/owl.theme.css' );\nwp_enqueue_style( 'owlcarousel-transitions', get_template_directory_uri() . '/inc/owl/owl.transitions.css' );\n</code></pre>\n\n<p>You do not need to enqueue both owl.carousel.js and the .min.js. Functionally these two files should be identical. The .js version is the full code that you would want to use in a development environment and the .min.js is a minimized version of the code optimized for smaller file size and is used in production environment.</p>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26413/" ]
I've been trying to integrate the [owl.carousel](http://owlgraphic.com/owlcarousel/#how-to) into my theme but can't get it to work. The instructions on the page are not for WordPress so I need help with how to properly enqueue the required files and calling (initializing) the carousel. I have added the following files to my themes directory located at **MyTheme/inc/owl/** * AjaxLoader.gif * grabbing.png * owl.carousel.css * owl.carousel.js * owl.carousel.min.js * owl.carouselinit.js *-> This is the "call the Owl initializer function"* * owl.theme.css * owl.transitions.css In my functions.php file I enqueue the required files: ``` /*------------------------------------------------------------------------------- Add Owl Carousel -------------------------------------------------------------------------------*/ // Enqueue Scripts/Styles for our owl.carousel.2 function agencyclix_add_owlcarousel() { wp_enqueue_script ( 'jquery' ); wp_enqueue_script( 'owlcarousel', get_template_directory_uri() . '/inc/owl/owl.carousel.js', array( 'jquery' ), false, true ); wp_enqueue_script( 'owlcarousel', get_template_directory_uri() . '/inc/owl/owl.carousel.min.js', array( 'jquery' ), false, true ); wp_enqueue_script( 'owl-carousel', get_template_directory_uri() . '/inc/owl/owl.carousel-init.js', array( 'jquery' ), false, true ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.carousel.css' ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.theme.css' ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.transitions.css' ); } add_action( 'wp_enqueue_scripts', 'agencyclix_add_owlcarousel' ); ``` In the file "owl.carouselinit.js" I simply added the initializer function listed at the website which is: ``` $(document).ready(function(){ $('.owl-carousel').owlCarousel(); }); ``` Also I have looked at some plugins that use owl carousel and it looks like they are only using (enqueue) 3 files to use the owl carousel. Thanks in advanced
You're reusing handles for the script and the styles. These need to be unique values (see [WP Codex Reference](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)) It should look something like this: ``` wp_enqueue_script( 'owlcarousel', get_template_directory_uri() . '/inc/owl/owl.carousel.min.js', array( 'jquery' ), false, true ); wp_enqueue_script( 'owlcarousel-init', get_template_directory_uri() . '/inc/owl/owl.carousel-init.js', array( 'jquery' ), false, true ); wp_enqueue_style( 'owlcarousel-style', get_template_directory_uri() . '/inc/owl/owl.carousel.css' ); wp_enqueue_style( 'owlcarousel-theme', get_template_directory_uri() . '/inc/owl/owl.theme.css' ); wp_enqueue_style( 'owlcarousel-transitions', get_template_directory_uri() . '/inc/owl/owl.transitions.css' ); ``` You do not need to enqueue both owl.carousel.js and the .min.js. Functionally these two files should be identical. The .js version is the full code that you would want to use in a development environment and the .min.js is a minimized version of the code optimized for smaller file size and is used in production environment.
180,353
<p>im try something with the upload_dir filter</p> <p>I check the current CPT with this function </p> <pre><code> function get_current_post_type() { global $post, $typenow, $current_screen; //we have a post so we can just get the post type from that if ( $post &amp;&amp; $post-&gt;post_type ) { return $post-&gt;post_type; } //check the global $typenow - set in admin.php elseif ( $typenow ) { return $typenow; } //check the global $current_screen object - set in sceen.php elseif ( $current_screen &amp;&amp; $current_screen-&gt;post_type ) { return $current_screen-&gt;post_type; } //lastly check the post_type querystring elseif ( isset( $_REQUEST['post_type'] ) ) { return sanitize_key( $_REQUEST['post_type'] ); } //we do not know the post type! return NULL; } </code></pre> <p>now i want to change the 'upload_dir' on at a certain cpt called "rsg_download"</p> <pre><code>add_action( 'admin_init', 'call_from_admin' ); function call_from_admin() { //Here i get the Current custom Post type is the Post type = "rsg_download" then i want upload in a other folder called "rsg-uploads" $currentCPT = get_current_post_type(); if ( $currentCPT === 'rsg_download' ) { add_filter( 'upload_dir', 'change_upload_dir' ); } } </code></pre> <p>When i use only </p> <pre><code>$currentCPT = get_current_post_type(); if ( $currentCPT === 'rsg_download' ) { add_filter( 'upload_dir', 'change_upload_dir' ); } </code></pre> <p>The 'change_upload_dir' function is called twice dont know why also i call this from 'admin_init' with the function 'call_from_admin' and it calls only one time so far so good</p> <p>i go to my CPT "rsg_download" and the uploade files are in the right place at wp-content/uploads/rsg-uploads/ this works so far</p> <p>now i go to "Pages" and i upload a File but i want the files not in /rsg-upload but in the default path </p> <p>Function to change the upload_dir this function should only be called when the custom post type is 'rsg_download':</p> <pre><code> function change_upload_dir( $param ) { $mydir = '/rsg-uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; return $param; } </code></pre> <p>got some help from #wordpress in freenode but still not working for me :/ Current code i try the upload folder is still the standard one:</p> <pre><code> function get_current_post_type() { global $post, $typenow, $current_screen; if ( $post &amp;&amp; $post-&gt;post_type ) return $post-&gt;post_type; elseif( $typenow ) return $typenow; elseif( $current_screen &amp;&amp; $current_screen-&gt;post_type ) return $current_screen-&gt;post_type; elseif( isset( $_REQUEST['post_type'] ) ) return sanitize_key( $_REQUEST['post_type'] ); return null; } function custom_post_type_upload_directory( $args ) { if( 'rsg_download' == get_current_post_type() ) { $mydir = '/rsg-uploads'; $args['path'] = $args['basedir'] . $mydir; $args['url'] = $args['baseurl'] . $mydir; } return $args; } add_filter( 'upload_dir', 'custom_post_type_upload_directory' ); </code></pre>
[ { "answer_id": 180355, "author": "Dave Ross", "author_id": 3851, "author_profile": "https://wordpress.stackexchange.com/users/3851", "pm_score": 2, "selected": false, "text": "<p>In this code:</p>\n\n<pre><code>if ( $currentCPT = 'rsg_download' ) {\n</code></pre>\n\n<p>you're assigning the value <code>'rsg_download'</code> to <code>$currentCPT</code>. When you do an assignment inside an if(), the if() only sees the value you assigned. Since a non-empty string is always true, the body of the if() always executes. To test the value instead, you need to use <code>==</code> or even better <code>===</code> (see <a href=\"https://stackoverflow.com/questions/2063480/the-3-different-equals?rq=1\">https://stackoverflow.com/questions/2063480/the-3-different-equals?rq=1</a>).</p>\n\n<p>However, once you've called <code>add_filter</code>, it will run your function every time that filter is called for the rest of the page. And it may be called multiple times if the upload directory is needed in more than one place on the page.</p>\n\n<p>You need to move your CPT check inside your <code>change_upload_dir</code> function:</p>\n\n<pre><code>function change_upload_dir( $param ) {\n\n $currentCPT = get_current_post_type();\n if ( $currentCPT === 'rsg_download' ) {\n\n $mydir = '/rsg-uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n\n }\n\n return $param;\n\n}\n</code></pre>\n\n<p>Then you can get rid of the if() around add_filter and let it be called all the time.</p>\n" }, { "answer_id": 180703, "author": "cannap", "author_id": 68663, "author_profile": "https://wordpress.stackexchange.com/users/68663", "pm_score": 4, "selected": true, "text": "<p>I found! this will only change the upload dir when upload in the \"rsg_download\" CPT</p>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );\nfunction rsg_pre_upload( $file ) {\n add_filter( 'upload_dir', 'rsg_custom_upload_dir' );\n return $file;\n}\n\nfunction rsg_custom_upload_dir( $param ) {\n $id = $_REQUEST['post_id'];\n $parent = get_post( $id )-&gt;post_parent;\n if( \"rsg_download\" == get_post_type( $id ) || \"rsg_download\" == get_post_type( $parent ) ) {\n $mydir = '/rsg-uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n }\n return $param;\n\n\n}\n</code></pre>\n\n<p>i got some trouble when i used any Framework for creating Metaboxes i tried Vafpress Redux CBM2 but the Problem was on my side </p>\n\n<p>here is how i got working for any custom upload fields </p>\n\n<pre><code>function rsg_custom_upload_dir( $param ) {\n\n$current_page = $_SERVER['HTTP_REFERER'];\n$id = $_REQUEST['post_id'];\n$parent = get_post( $id )-&gt;post_parent;\n\n\n\nif ( \"rsg_download\" == get_post_type( $id ) || \"rsg_download\" == get_post_type( $parent ) ) {\n $mydir = '/rsg_uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n\n} elseif ( strpos( $current_page, 'rsg_download' ) ) {\n $mydir = '/rsg_uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n\n}\n\nreturn $param;\n\n}\n</code></pre>\n" }, { "answer_id": 268736, "author": "David", "author_id": 120864, "author_profile": "https://wordpress.stackexchange.com/users/120864", "pm_score": 2, "selected": false, "text": "<p><strong>Based on the above solution, this one works with CPT and uploads based on Y/M structures:</strong></p>\n\n<pre><code>\n add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );\nfunction rsg_pre_upload( $file ) {\n add_filter( 'upload_dir', 'rsg_custom_upload_dir' );\n return $file;\n}\n\nfunction rsg_custom_upload_dir( $param ) {\n $id = $_REQUEST['post_id'];\n $parent = get_post( $id )->post_parent;\n if( \"artwork\" == get_post_type( $id ) || \"artwork\" == get_post_type( $parent ) ) {\n\n $param['subdir'] = '/artworks' . $param['subdir'];\n $param['path'] = $param['basedir'] . $param['subdir'];\n $param['url'] = $param['baseurl'] . $param['subdir'];\n }\n return $param;\n\n}\n</code></pre>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180353", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68663/" ]
im try something with the upload\_dir filter I check the current CPT with this function ``` function get_current_post_type() { global $post, $typenow, $current_screen; //we have a post so we can just get the post type from that if ( $post && $post->post_type ) { return $post->post_type; } //check the global $typenow - set in admin.php elseif ( $typenow ) { return $typenow; } //check the global $current_screen object - set in sceen.php elseif ( $current_screen && $current_screen->post_type ) { return $current_screen->post_type; } //lastly check the post_type querystring elseif ( isset( $_REQUEST['post_type'] ) ) { return sanitize_key( $_REQUEST['post_type'] ); } //we do not know the post type! return NULL; } ``` now i want to change the 'upload\_dir' on at a certain cpt called "rsg\_download" ``` add_action( 'admin_init', 'call_from_admin' ); function call_from_admin() { //Here i get the Current custom Post type is the Post type = "rsg_download" then i want upload in a other folder called "rsg-uploads" $currentCPT = get_current_post_type(); if ( $currentCPT === 'rsg_download' ) { add_filter( 'upload_dir', 'change_upload_dir' ); } } ``` When i use only ``` $currentCPT = get_current_post_type(); if ( $currentCPT === 'rsg_download' ) { add_filter( 'upload_dir', 'change_upload_dir' ); } ``` The 'change\_upload\_dir' function is called twice dont know why also i call this from 'admin\_init' with the function 'call\_from\_admin' and it calls only one time so far so good i go to my CPT "rsg\_download" and the uploade files are in the right place at wp-content/uploads/rsg-uploads/ this works so far now i go to "Pages" and i upload a File but i want the files not in /rsg-upload but in the default path Function to change the upload\_dir this function should only be called when the custom post type is 'rsg\_download': ``` function change_upload_dir( $param ) { $mydir = '/rsg-uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; return $param; } ``` got some help from #wordpress in freenode but still not working for me :/ Current code i try the upload folder is still the standard one: ``` function get_current_post_type() { global $post, $typenow, $current_screen; if ( $post && $post->post_type ) return $post->post_type; elseif( $typenow ) return $typenow; elseif( $current_screen && $current_screen->post_type ) return $current_screen->post_type; elseif( isset( $_REQUEST['post_type'] ) ) return sanitize_key( $_REQUEST['post_type'] ); return null; } function custom_post_type_upload_directory( $args ) { if( 'rsg_download' == get_current_post_type() ) { $mydir = '/rsg-uploads'; $args['path'] = $args['basedir'] . $mydir; $args['url'] = $args['baseurl'] . $mydir; } return $args; } add_filter( 'upload_dir', 'custom_post_type_upload_directory' ); ```
I found! this will only change the upload dir when upload in the "rsg\_download" CPT ``` add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' ); function rsg_pre_upload( $file ) { add_filter( 'upload_dir', 'rsg_custom_upload_dir' ); return $file; } function rsg_custom_upload_dir( $param ) { $id = $_REQUEST['post_id']; $parent = get_post( $id )->post_parent; if( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) { $mydir = '/rsg-uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; } return $param; } ``` i got some trouble when i used any Framework for creating Metaboxes i tried Vafpress Redux CBM2 but the Problem was on my side here is how i got working for any custom upload fields ``` function rsg_custom_upload_dir( $param ) { $current_page = $_SERVER['HTTP_REFERER']; $id = $_REQUEST['post_id']; $parent = get_post( $id )->post_parent; if ( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) { $mydir = '/rsg_uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; } elseif ( strpos( $current_page, 'rsg_download' ) ) { $mydir = '/rsg_uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; } return $param; } ```
180,363
<p>I'm optimizing a WordPress site. For this, I have created a function that remove the old sticky posts. This function doesn't work correctly in some cases. Sometimes all sticky's are removed (so no sticky is set). Is there anyone who could see what this causes?</p> <pre><code>add_action( 'publish_post', 'wf_clean_sticky', 10, 2); function wf_clean_sticky($post_id, $post) { //disable function on autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return; } // check if current post is sticky if(isset($_POST['sticky']) &amp;&amp; ($_POST['sticky'] == 'sticky')) { $array = array($post_id); update_option('sticky_posts', $array); unset($_POST['sticky']); } } </code></pre> <p>I've already tried to hook on another functions (e.g. save_post and edit_post) and create a log function for debugging that stores the $_POST to see if there is anything wrong, but I don't get it..</p>
[ { "answer_id": 180355, "author": "Dave Ross", "author_id": 3851, "author_profile": "https://wordpress.stackexchange.com/users/3851", "pm_score": 2, "selected": false, "text": "<p>In this code:</p>\n\n<pre><code>if ( $currentCPT = 'rsg_download' ) {\n</code></pre>\n\n<p>you're assigning the value <code>'rsg_download'</code> to <code>$currentCPT</code>. When you do an assignment inside an if(), the if() only sees the value you assigned. Since a non-empty string is always true, the body of the if() always executes. To test the value instead, you need to use <code>==</code> or even better <code>===</code> (see <a href=\"https://stackoverflow.com/questions/2063480/the-3-different-equals?rq=1\">https://stackoverflow.com/questions/2063480/the-3-different-equals?rq=1</a>).</p>\n\n<p>However, once you've called <code>add_filter</code>, it will run your function every time that filter is called for the rest of the page. And it may be called multiple times if the upload directory is needed in more than one place on the page.</p>\n\n<p>You need to move your CPT check inside your <code>change_upload_dir</code> function:</p>\n\n<pre><code>function change_upload_dir( $param ) {\n\n $currentCPT = get_current_post_type();\n if ( $currentCPT === 'rsg_download' ) {\n\n $mydir = '/rsg-uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n\n }\n\n return $param;\n\n}\n</code></pre>\n\n<p>Then you can get rid of the if() around add_filter and let it be called all the time.</p>\n" }, { "answer_id": 180703, "author": "cannap", "author_id": 68663, "author_profile": "https://wordpress.stackexchange.com/users/68663", "pm_score": 4, "selected": true, "text": "<p>I found! this will only change the upload dir when upload in the \"rsg_download\" CPT</p>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );\nfunction rsg_pre_upload( $file ) {\n add_filter( 'upload_dir', 'rsg_custom_upload_dir' );\n return $file;\n}\n\nfunction rsg_custom_upload_dir( $param ) {\n $id = $_REQUEST['post_id'];\n $parent = get_post( $id )-&gt;post_parent;\n if( \"rsg_download\" == get_post_type( $id ) || \"rsg_download\" == get_post_type( $parent ) ) {\n $mydir = '/rsg-uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n }\n return $param;\n\n\n}\n</code></pre>\n\n<p>i got some trouble when i used any Framework for creating Metaboxes i tried Vafpress Redux CBM2 but the Problem was on my side </p>\n\n<p>here is how i got working for any custom upload fields </p>\n\n<pre><code>function rsg_custom_upload_dir( $param ) {\n\n$current_page = $_SERVER['HTTP_REFERER'];\n$id = $_REQUEST['post_id'];\n$parent = get_post( $id )-&gt;post_parent;\n\n\n\nif ( \"rsg_download\" == get_post_type( $id ) || \"rsg_download\" == get_post_type( $parent ) ) {\n $mydir = '/rsg_uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n\n} elseif ( strpos( $current_page, 'rsg_download' ) ) {\n $mydir = '/rsg_uploads';\n $param['path'] = $param['basedir'] . $mydir;\n $param['url'] = $param['baseurl'] . $mydir;\n\n}\n\nreturn $param;\n\n}\n</code></pre>\n" }, { "answer_id": 268736, "author": "David", "author_id": 120864, "author_profile": "https://wordpress.stackexchange.com/users/120864", "pm_score": 2, "selected": false, "text": "<p><strong>Based on the above solution, this one works with CPT and uploads based on Y/M structures:</strong></p>\n\n<pre><code>\n add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );\nfunction rsg_pre_upload( $file ) {\n add_filter( 'upload_dir', 'rsg_custom_upload_dir' );\n return $file;\n}\n\nfunction rsg_custom_upload_dir( $param ) {\n $id = $_REQUEST['post_id'];\n $parent = get_post( $id )->post_parent;\n if( \"artwork\" == get_post_type( $id ) || \"artwork\" == get_post_type( $parent ) ) {\n\n $param['subdir'] = '/artworks' . $param['subdir'];\n $param['path'] = $param['basedir'] . $param['subdir'];\n $param['url'] = $param['baseurl'] . $param['subdir'];\n }\n return $param;\n\n}\n</code></pre>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68668/" ]
I'm optimizing a WordPress site. For this, I have created a function that remove the old sticky posts. This function doesn't work correctly in some cases. Sometimes all sticky's are removed (so no sticky is set). Is there anyone who could see what this causes? ``` add_action( 'publish_post', 'wf_clean_sticky', 10, 2); function wf_clean_sticky($post_id, $post) { //disable function on autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } // check if current post is sticky if(isset($_POST['sticky']) && ($_POST['sticky'] == 'sticky')) { $array = array($post_id); update_option('sticky_posts', $array); unset($_POST['sticky']); } } ``` I've already tried to hook on another functions (e.g. save\_post and edit\_post) and create a log function for debugging that stores the $\_POST to see if there is anything wrong, but I don't get it..
I found! this will only change the upload dir when upload in the "rsg\_download" CPT ``` add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' ); function rsg_pre_upload( $file ) { add_filter( 'upload_dir', 'rsg_custom_upload_dir' ); return $file; } function rsg_custom_upload_dir( $param ) { $id = $_REQUEST['post_id']; $parent = get_post( $id )->post_parent; if( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) { $mydir = '/rsg-uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; } return $param; } ``` i got some trouble when i used any Framework for creating Metaboxes i tried Vafpress Redux CBM2 but the Problem was on my side here is how i got working for any custom upload fields ``` function rsg_custom_upload_dir( $param ) { $current_page = $_SERVER['HTTP_REFERER']; $id = $_REQUEST['post_id']; $parent = get_post( $id )->post_parent; if ( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) { $mydir = '/rsg_uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; } elseif ( strpos( $current_page, 'rsg_download' ) ) { $mydir = '/rsg_uploads'; $param['path'] = $param['basedir'] . $mydir; $param['url'] = $param['baseurl'] . $mydir; } return $param; } ```
180,385
<p>I have PHP code as </p> <pre><code>$message = str_replace("{eventlinkURL}",$eventlinkURL,$message); </code></pre> <p>I want to set color to the <code>$eventlinkURL</code> variable. I tried using <code>&lt;font&gt;</code> </p> <pre><code>echo "&lt;font style='background:red'&gt; &lt;font color ='red'&gt; $message = str_replace('{eventlinkURL}',$eventlinkURL,$message); /&gt;"; </code></pre> <p>but no success. How do I set color to the variable?</p>
[ { "answer_id": 180391, "author": "Ituk", "author_id": 68680, "author_profile": "https://wordpress.stackexchange.com/users/68680", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p>do not use <code>&lt;font&gt;</code> html tag, it is old and i'm not even sure if can work in modern browsers. instead use <code>&lt;span&gt;</code> (for inline text) or <code>&lt;p&gt;</code> (for paragraph).</p></li>\n<li><p>php and html can work together but there's an appropriate way to write it.\ngenerally speaking, html code is wrapped with double quotes <code>\"html\"</code> and php with periods <code>.php.</code>:</p>\n\n<pre><code>echo \"html code here\".php code here.\"more html here\";\n</code></pre></li>\n<li><p>i advice you first to set a variable for the <code>$message</code> and after it call the var inside the echo code. that way it would be a cleaner code.</p></li>\n</ol>\n\n<p>so here is a final solution for you:</p>\n\n<pre><code>$message = str_replace('{eventlinkURL}',$eventlinkURL,$message); \necho \"&lt;span style='background:red;'&gt;\".$message.\"&lt;/span&gt;\";\n</code></pre>\n\n<p>good luck,</p>\n\n<p>Ituk</p>\n" }, { "answer_id": 180400, "author": "Joe Z", "author_id": 68686, "author_profile": "https://wordpress.stackexchange.com/users/68686", "pm_score": 0, "selected": false, "text": "<p>Instead of using style background:red; use color:red; like the following.</p>\n\n<pre><code>$message = str_replace('{eventlinkURL}',$eventlinkURL,$message); \necho \"&lt;span style='color:red;'&gt;\".$message.\"&lt;/span&gt;\";\n</code></pre>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180385", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68679/" ]
I have PHP code as ``` $message = str_replace("{eventlinkURL}",$eventlinkURL,$message); ``` I want to set color to the `$eventlinkURL` variable. I tried using `<font>` ``` echo "<font style='background:red'> <font color ='red'> $message = str_replace('{eventlinkURL}',$eventlinkURL,$message); />"; ``` but no success. How do I set color to the variable?
1. do not use `<font>` html tag, it is old and i'm not even sure if can work in modern browsers. instead use `<span>` (for inline text) or `<p>` (for paragraph). 2. php and html can work together but there's an appropriate way to write it. generally speaking, html code is wrapped with double quotes `"html"` and php with periods `.php.`: ``` echo "html code here".php code here."more html here"; ``` 3. i advice you first to set a variable for the `$message` and after it call the var inside the echo code. that way it would be a cleaner code. so here is a final solution for you: ``` $message = str_replace('{eventlinkURL}',$eventlinkURL,$message); echo "<span style='background:red;'>".$message."</span>"; ``` good luck, Ituk
180,397
<p>I don't know how to do it, but I have a few js code blocks in my sites header like the StatCounter tracking code, facebook like button js code, etc.</p> <p>Now the thing is that I want to combine all the external js code blocks into one file so that I can add it either in the header or footer section. Can any one guide me on how can I add these code blocks into a single file?</p>
[ { "answer_id": 180391, "author": "Ituk", "author_id": 68680, "author_profile": "https://wordpress.stackexchange.com/users/68680", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p>do not use <code>&lt;font&gt;</code> html tag, it is old and i'm not even sure if can work in modern browsers. instead use <code>&lt;span&gt;</code> (for inline text) or <code>&lt;p&gt;</code> (for paragraph).</p></li>\n<li><p>php and html can work together but there's an appropriate way to write it.\ngenerally speaking, html code is wrapped with double quotes <code>\"html\"</code> and php with periods <code>.php.</code>:</p>\n\n<pre><code>echo \"html code here\".php code here.\"more html here\";\n</code></pre></li>\n<li><p>i advice you first to set a variable for the <code>$message</code> and after it call the var inside the echo code. that way it would be a cleaner code.</p></li>\n</ol>\n\n<p>so here is a final solution for you:</p>\n\n<pre><code>$message = str_replace('{eventlinkURL}',$eventlinkURL,$message); \necho \"&lt;span style='background:red;'&gt;\".$message.\"&lt;/span&gt;\";\n</code></pre>\n\n<p>good luck,</p>\n\n<p>Ituk</p>\n" }, { "answer_id": 180400, "author": "Joe Z", "author_id": 68686, "author_profile": "https://wordpress.stackexchange.com/users/68686", "pm_score": 0, "selected": false, "text": "<p>Instead of using style background:red; use color:red; like the following.</p>\n\n<pre><code>$message = str_replace('{eventlinkURL}',$eventlinkURL,$message); \necho \"&lt;span style='color:red;'&gt;\".$message.\"&lt;/span&gt;\";\n</code></pre>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180397", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68685/" ]
I don't know how to do it, but I have a few js code blocks in my sites header like the StatCounter tracking code, facebook like button js code, etc. Now the thing is that I want to combine all the external js code blocks into one file so that I can add it either in the header or footer section. Can any one guide me on how can I add these code blocks into a single file?
1. do not use `<font>` html tag, it is old and i'm not even sure if can work in modern browsers. instead use `<span>` (for inline text) or `<p>` (for paragraph). 2. php and html can work together but there's an appropriate way to write it. generally speaking, html code is wrapped with double quotes `"html"` and php with periods `.php.`: ``` echo "html code here".php code here."more html here"; ``` 3. i advice you first to set a variable for the `$message` and after it call the var inside the echo code. that way it would be a cleaner code. so here is a final solution for you: ``` $message = str_replace('{eventlinkURL}',$eventlinkURL,$message); echo "<span style='background:red;'>".$message."</span>"; ``` good luck, Ituk
180,411
<p>I am building a plugin which loads a form into a table cell when clicked. </p> <p>Here is the AJAX:</p> <pre><code> public static function cp_libhours_ajax(){ ?&gt; &lt;script&gt; jQuery(document).ready(function(){ jQuery('.libhours-row a').click(function(e){ e.preventDefault(); //don't let the link click through //this is the cell in which the form will be placed var cellToReplace = jQuery(this).parent('td').prop('className'); //extract the values of the parameters passed in the URL var querystring = jQuery(this).prop('href').split("?")[1]; var values = querystring.split("&amp;"); var count = 0; var param = []; jQuery(values).each(function(index, element) { param[count] = element.split("=")[1]; count++; }); //data object to be passed to the ajac function var data = { 'action': 'cp_libhours_ajax', 'semester': param[0], 'day_of_week': param[1] }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(ajaxurl, data, function(response) { jQuery('.' + cellToReplace).html(response); }); }); }); &lt;/script&gt; </code></pre> <p>Here is the response generated from the callback function: </p> <pre><code>/** * CALLED VIA AJAX! * * within public static function cp_libhours_ajax() */ public static function cp_libhours_ajax_callback() { global $wpdb; // this is how you get access to the database $semester = $_POST['semester']; $day_of_week = $_POST['day_of_week']; $output = ' &lt;form method="post" action="'.admin_url('admin-post.php').'"&gt; '.wp_nonce_field('cp_libhours_pest_control','cp_libhours_pest_control_field').' &lt;fieldset&gt; &lt;p class="clearfix"&gt; &lt;label for="regular_open"&gt;Open:&lt;/label&gt; &lt;input type="text" id="regular_open" name="regular_open" class="timepicker"&gt; &lt;label for="regular_close" &gt;Close: &lt;input type="text" id="regular_close" name="regular_close" class="timepicker"&gt; &lt;/label&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="checkbox" id="regular_24" name="regular_24"&gt; 24-HR &lt;input type="checkbox" id="regular_closed" name="regular_closed"&gt; Closed &lt;/p&gt; &lt;div&gt; &lt;button type="submit"&gt;Save&lt;/button&gt; &lt;button type="reset"&gt;Cancel&lt;/button&gt; &lt;input type="hidden" name="semester" value="'.$semester.'"&gt; &lt;input type="hidden" name="day_of_week" value="'.$day_of_week.'"&gt; &lt;input type="hidden" name="action_type" value="add_regular_hour"&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;input type="hidden" name="action" value="hours_action"&gt; &lt;input type="hidden" name="first_year" value="2014"&gt; &lt;input type="hidden" name="area_id" value="1"&gt; &lt;/form&gt; '; echo $output; wp_die(); // this is required to terminate immediately and return a proper response } </code></pre> <p>The form shows up just fine on the page. However, when it is time to submit, the form does not go to the specified link in the action tag (admin-post.php), but rather, to admin-ajax.php. I get a white page with a '0'.</p>
[ { "answer_id": 180422, "author": "Ituk", "author_id": 68680, "author_profile": "https://wordpress.stackexchange.com/users/68680", "pm_score": 0, "selected": false, "text": "<p>try to add <code>return false;</code> after the ajax call. like this:</p>\n\n<pre><code> jQuery.post(ajaxurl, data, function(response) {\n jQuery('.' + cellToReplace).html(response);\n });\nreturn false;\n});\n</code></pre>\n\n<p>this way the ajax is called only once.</p>\n" }, { "answer_id": 239467, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>This happens because you specify in your ajax request a different url than you use in the form.</p>\n\n<pre><code>Query.post(ajaxurl, data, function(response) {\n</code></pre>\n\n<p>you don't show it in the code snippet but<code>ajaxurl</code> is usually set to be the <code>{site url}\\wp-admin\\admin-ajax.php</code>.</p>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68200/" ]
I am building a plugin which loads a form into a table cell when clicked. Here is the AJAX: ``` public static function cp_libhours_ajax(){ ?> <script> jQuery(document).ready(function(){ jQuery('.libhours-row a').click(function(e){ e.preventDefault(); //don't let the link click through //this is the cell in which the form will be placed var cellToReplace = jQuery(this).parent('td').prop('className'); //extract the values of the parameters passed in the URL var querystring = jQuery(this).prop('href').split("?")[1]; var values = querystring.split("&"); var count = 0; var param = []; jQuery(values).each(function(index, element) { param[count] = element.split("=")[1]; count++; }); //data object to be passed to the ajac function var data = { 'action': 'cp_libhours_ajax', 'semester': param[0], 'day_of_week': param[1] }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(ajaxurl, data, function(response) { jQuery('.' + cellToReplace).html(response); }); }); }); </script> ``` Here is the response generated from the callback function: ``` /** * CALLED VIA AJAX! * * within public static function cp_libhours_ajax() */ public static function cp_libhours_ajax_callback() { global $wpdb; // this is how you get access to the database $semester = $_POST['semester']; $day_of_week = $_POST['day_of_week']; $output = ' <form method="post" action="'.admin_url('admin-post.php').'"> '.wp_nonce_field('cp_libhours_pest_control','cp_libhours_pest_control_field').' <fieldset> <p class="clearfix"> <label for="regular_open">Open:</label> <input type="text" id="regular_open" name="regular_open" class="timepicker"> <label for="regular_close" >Close: <input type="text" id="regular_close" name="regular_close" class="timepicker"> </label> </p> <p> <input type="checkbox" id="regular_24" name="regular_24"> 24-HR <input type="checkbox" id="regular_closed" name="regular_closed"> Closed </p> <div> <button type="submit">Save</button> <button type="reset">Cancel</button> <input type="hidden" name="semester" value="'.$semester.'"> <input type="hidden" name="day_of_week" value="'.$day_of_week.'"> <input type="hidden" name="action_type" value="add_regular_hour"> </div> </fieldset> <input type="hidden" name="action" value="hours_action"> <input type="hidden" name="first_year" value="2014"> <input type="hidden" name="area_id" value="1"> </form> '; echo $output; wp_die(); // this is required to terminate immediately and return a proper response } ``` The form shows up just fine on the page. However, when it is time to submit, the form does not go to the specified link in the action tag (admin-post.php), but rather, to admin-ajax.php. I get a white page with a '0'.
This happens because you specify in your ajax request a different url than you use in the form. ``` Query.post(ajaxurl, data, function(response) { ``` you don't show it in the code snippet but`ajaxurl` is usually set to be the `{site url}\wp-admin\admin-ajax.php`.
180,417
<p>I'm using a <code>wp_query</code> to find custom posts that have a specified numeric value inside of a custom field. That custom field's value is an array of numbers (IDs of selected posts using Advanced Custom Field's Relationship field). </p> <p>So I am trying to find all posts that have the specified value inside of that field's array.</p> <p>Here's my code:</p> <pre><code>foreach ($selectedAuthors as $myAuthor){ $args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'resource', 'resource_types' =&gt; 'ml-special-reports', 'meta_query' =&gt; array ( 'key' =&gt; 'qd_resource_author_selector', 'value' =&gt; $myAuthor, ), 'orderby' =&gt; 'title', 'order' =&gt; 'ASC' ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { echo '&lt;h3&gt;'.get_the_title($myAuthor).'&lt;/h3&gt;'; while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); echo '&lt;h3&gt;'.get_the_title().'&lt;/h3&gt;'; endwhile; wp_reset_postdata(); } } </code></pre> <p>If I <code>var_dump()</code> <code>$selectedAuthors</code> I get:</p> <pre><code>array(3) { [0]=&gt; int(214) [1]=&gt; int(216) [2]=&gt; int(211) } </code></pre> <p>Each run through the <code>while($query-&gt;have_posts())</code> returns every post of the type <code>resource</code> with the <code>resource_types</code> taxonomy term <code>ml-special-reports</code> regardless of whether or not <code>$myAuthor</code> exists in the <code>qd_resource_author_selector</code> custom field's array.</p> <p>Any thoughts on what I'm doing wrong?</p>
[ { "answer_id": 180434, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>First of all, your <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\"><code>meta_query</code></a> is wrong. It should be an array of an array, not just an array</p>\n\n<p>So, the following </p>\n\n<pre><code>'meta_query' =&gt; array (\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; $myAuthor,\n),\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>'meta_query' =&gt; array (\n array(\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; $myAuthor,\n ),\n),\n</code></pre>\n\n<p>Secondly, you can optimize your query. You are running a query for every value. If you have 100 values, you are going to run 100 queries which is expensive</p>\n\n<p>You can optimize your query by adding your values in an array and passing the array directly to your <code>meta_query</code></p>\n\n<h2>Just a few other concerns</h2>\n\n<ul>\n<li><p>Run a proper <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\"><code>tax_query</code></a>. The syntax you are using is depreciated</p></li>\n<li><p>Your first instance of <a href=\"http://codex.wordpress.org/Function_Reference/get_the_title\" rel=\"nofollow\"><code>get_the_title()</code></a> looks out of place outside the loop. Not sure what you are doing there</p></li>\n<li><p>Do not mix your syntax, it is confusing and really hard to debug on failure. For your <code>if</code> statement you are using curlies (which I prefer as basically all editors support them, very easy to debug) and in your <code>while</code> statement you use <code>:</code> and <code>endwhile</code>. I would recommend that you use curlies and stick with them in future</p></li>\n</ul>\n\n<p>With all said, you can try something like this without a <code>foreach</code> loop</p>\n\n<pre><code>$myAuthor = array('value1', 'value2', 'value3');\n$args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'resource',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'resource_types',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'ml-special-reports',\n ),\n ),\n 'meta_query' =&gt; array (\n array(\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; $myAuthor,\n 'compare' =&gt; 'IN',\n ),\n ),\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n);\n$query = new WP_Query( $args );\nif ( $query-&gt;have_posts() ) { \n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n echo '&lt;h3&gt;'.get_the_title().'&lt;/h3&gt;';\n }\n wp_reset_postdata();\n}\n</code></pre>\n" }, { "answer_id": 180610, "author": "Joe", "author_id": 34273, "author_profile": "https://wordpress.stackexchange.com/users/34273", "pm_score": 1, "selected": true, "text": "<p>I solved it using some of Pieter Goosen's code, and taking a closer look at the field's value in SQL. It was saving the information in a strange manner that required me to wrap the value in quotation marks to return the correct posts.</p>\n\n<p>Here's the working code:</p>\n\n<pre><code>foreach ($selectedAuthors as $myAuthor){\n echo '&lt;hr /&gt;&lt;p&gt;my author = '.$myAuthor.'&lt;/p&gt;'; \n $args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'resource',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'resource_types',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'ml-special-reports',\n ),\n ),\n 'meta_query' =&gt; array (\n array(\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; '\"'.$myAuthor.'\"',\n 'compare' =&gt; 'LIKE', \n ),\n ),\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n );\n $query = new WP_Query( $args );\n if ( $query-&gt;have_posts() ) { \n echo '&lt;h3&gt;'.get_the_title($myAuthor).'&lt;/h3&gt;';\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n echo '&lt;h3&gt;'.get_the_title().'&lt;/h3&gt;';\n }\n wp_reset_postdata();\n }\n}\n</code></pre>\n\n<p>So on this line I had to force quotation marks to appear: </p>\n\n<pre><code>'value' =&gt; '\"'.$myAuthor.'\"',\n</code></pre>\n\n<p>Now it returns the Author's name, and then the name of each post with the correct taxonomy term that they are assigned to.</p>\n" } ]
2015/03/06
[ "https://wordpress.stackexchange.com/questions/180417", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34273/" ]
I'm using a `wp_query` to find custom posts that have a specified numeric value inside of a custom field. That custom field's value is an array of numbers (IDs of selected posts using Advanced Custom Field's Relationship field). So I am trying to find all posts that have the specified value inside of that field's array. Here's my code: ``` foreach ($selectedAuthors as $myAuthor){ $args = array( 'posts_per_page' => -1, 'post_type' => 'resource', 'resource_types' => 'ml-special-reports', 'meta_query' => array ( 'key' => 'qd_resource_author_selector', 'value' => $myAuthor, ), 'orderby' => 'title', 'order' => 'ASC' ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { echo '<h3>'.get_the_title($myAuthor).'</h3>'; while ( $query->have_posts() ) : $query->the_post(); echo '<h3>'.get_the_title().'</h3>'; endwhile; wp_reset_postdata(); } } ``` If I `var_dump()` `$selectedAuthors` I get: ``` array(3) { [0]=> int(214) [1]=> int(216) [2]=> int(211) } ``` Each run through the `while($query->have_posts())` returns every post of the type `resource` with the `resource_types` taxonomy term `ml-special-reports` regardless of whether or not `$myAuthor` exists in the `qd_resource_author_selector` custom field's array. Any thoughts on what I'm doing wrong?
I solved it using some of Pieter Goosen's code, and taking a closer look at the field's value in SQL. It was saving the information in a strange manner that required me to wrap the value in quotation marks to return the correct posts. Here's the working code: ``` foreach ($selectedAuthors as $myAuthor){ echo '<hr /><p>my author = '.$myAuthor.'</p>'; $args = array( 'posts_per_page' => -1, 'post_type' => 'resource', 'tax_query' => array( array( 'taxonomy' => 'resource_types', 'field' => 'slug', 'terms' => 'ml-special-reports', ), ), 'meta_query' => array ( array( 'key' => 'qd_resource_author_selector', 'value' => '"'.$myAuthor.'"', 'compare' => 'LIKE', ), ), 'orderby' => 'title', 'order' => 'ASC' ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { echo '<h3>'.get_the_title($myAuthor).'</h3>'; while ( $query->have_posts() ) { $query->the_post(); echo '<h3>'.get_the_title().'</h3>'; } wp_reset_postdata(); } } ``` So on this line I had to force quotation marks to appear: ``` 'value' => '"'.$myAuthor.'"', ``` Now it returns the Author's name, and then the name of each post with the correct taxonomy term that they are assigned to.
180,437
<p>I've been trying to figure out this problem for a while now:</p> <pre><code>&lt;article class="post"&gt; &lt;div class="entry-header"&gt; &lt;h2 class="entry-title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;/div&gt; &lt;!-- end entry-header --&gt; &lt;div class="entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;!-- end entry-content --&gt; &lt;/article&gt; </code></pre> <p>This display the title, then the image (audio, video, gallery embed, etc.), then the post info. I am trying to get the Image, then the Title, and then the post info.</p> <p>I made this picture for what I explained.</p> <p><img src="https://i.stack.imgur.com/vDf0e.jpg" alt="enter image description here"></p> <p>How do I go about this?</p>
[ { "answer_id": 180434, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>First of all, your <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\"><code>meta_query</code></a> is wrong. It should be an array of an array, not just an array</p>\n\n<p>So, the following </p>\n\n<pre><code>'meta_query' =&gt; array (\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; $myAuthor,\n),\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>'meta_query' =&gt; array (\n array(\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; $myAuthor,\n ),\n),\n</code></pre>\n\n<p>Secondly, you can optimize your query. You are running a query for every value. If you have 100 values, you are going to run 100 queries which is expensive</p>\n\n<p>You can optimize your query by adding your values in an array and passing the array directly to your <code>meta_query</code></p>\n\n<h2>Just a few other concerns</h2>\n\n<ul>\n<li><p>Run a proper <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\"><code>tax_query</code></a>. The syntax you are using is depreciated</p></li>\n<li><p>Your first instance of <a href=\"http://codex.wordpress.org/Function_Reference/get_the_title\" rel=\"nofollow\"><code>get_the_title()</code></a> looks out of place outside the loop. Not sure what you are doing there</p></li>\n<li><p>Do not mix your syntax, it is confusing and really hard to debug on failure. For your <code>if</code> statement you are using curlies (which I prefer as basically all editors support them, very easy to debug) and in your <code>while</code> statement you use <code>:</code> and <code>endwhile</code>. I would recommend that you use curlies and stick with them in future</p></li>\n</ul>\n\n<p>With all said, you can try something like this without a <code>foreach</code> loop</p>\n\n<pre><code>$myAuthor = array('value1', 'value2', 'value3');\n$args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'resource',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'resource_types',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'ml-special-reports',\n ),\n ),\n 'meta_query' =&gt; array (\n array(\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; $myAuthor,\n 'compare' =&gt; 'IN',\n ),\n ),\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n);\n$query = new WP_Query( $args );\nif ( $query-&gt;have_posts() ) { \n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n echo '&lt;h3&gt;'.get_the_title().'&lt;/h3&gt;';\n }\n wp_reset_postdata();\n}\n</code></pre>\n" }, { "answer_id": 180610, "author": "Joe", "author_id": 34273, "author_profile": "https://wordpress.stackexchange.com/users/34273", "pm_score": 1, "selected": true, "text": "<p>I solved it using some of Pieter Goosen's code, and taking a closer look at the field's value in SQL. It was saving the information in a strange manner that required me to wrap the value in quotation marks to return the correct posts.</p>\n\n<p>Here's the working code:</p>\n\n<pre><code>foreach ($selectedAuthors as $myAuthor){\n echo '&lt;hr /&gt;&lt;p&gt;my author = '.$myAuthor.'&lt;/p&gt;'; \n $args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'resource',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'resource_types',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'ml-special-reports',\n ),\n ),\n 'meta_query' =&gt; array (\n array(\n 'key' =&gt; 'qd_resource_author_selector',\n 'value' =&gt; '\"'.$myAuthor.'\"',\n 'compare' =&gt; 'LIKE', \n ),\n ),\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n );\n $query = new WP_Query( $args );\n if ( $query-&gt;have_posts() ) { \n echo '&lt;h3&gt;'.get_the_title($myAuthor).'&lt;/h3&gt;';\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n echo '&lt;h3&gt;'.get_the_title().'&lt;/h3&gt;';\n }\n wp_reset_postdata();\n }\n}\n</code></pre>\n\n<p>So on this line I had to force quotation marks to appear: </p>\n\n<pre><code>'value' =&gt; '\"'.$myAuthor.'\"',\n</code></pre>\n\n<p>Now it returns the Author's name, and then the name of each post with the correct taxonomy term that they are assigned to.</p>\n" } ]
2015/03/07
[ "https://wordpress.stackexchange.com/questions/180437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38796/" ]
I've been trying to figure out this problem for a while now: ``` <article class="post"> <div class="entry-header"> <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> </div> <!-- end entry-header --> <div class="entry-content"> <?php the_content(); ?> </div> <!-- end entry-content --> </article> ``` This display the title, then the image (audio, video, gallery embed, etc.), then the post info. I am trying to get the Image, then the Title, and then the post info. I made this picture for what I explained. ![enter image description here](https://i.stack.imgur.com/vDf0e.jpg) How do I go about this?
I solved it using some of Pieter Goosen's code, and taking a closer look at the field's value in SQL. It was saving the information in a strange manner that required me to wrap the value in quotation marks to return the correct posts. Here's the working code: ``` foreach ($selectedAuthors as $myAuthor){ echo '<hr /><p>my author = '.$myAuthor.'</p>'; $args = array( 'posts_per_page' => -1, 'post_type' => 'resource', 'tax_query' => array( array( 'taxonomy' => 'resource_types', 'field' => 'slug', 'terms' => 'ml-special-reports', ), ), 'meta_query' => array ( array( 'key' => 'qd_resource_author_selector', 'value' => '"'.$myAuthor.'"', 'compare' => 'LIKE', ), ), 'orderby' => 'title', 'order' => 'ASC' ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { echo '<h3>'.get_the_title($myAuthor).'</h3>'; while ( $query->have_posts() ) { $query->the_post(); echo '<h3>'.get_the_title().'</h3>'; } wp_reset_postdata(); } } ``` So on this line I had to force quotation marks to appear: ``` 'value' => '"'.$myAuthor.'"', ``` Now it returns the Author's name, and then the name of each post with the correct taxonomy term that they are assigned to.
180,450
<p>I have a custom field that contains links in them and I want to auto add nofollow to those links in that custom field only. How can I do this?</p> <p>Example custom field value:</p> <pre><code>&lt;a href="http://www.uploadable.ch/file/PnvbZ2k8B4ku/[Raizel]_Medaka_Box_01v2_(BD_720p_AAC)_(1A92BFA4).mkv"&gt;[Raizel]_Medaka_Box_01v2_(BD_720p_AAC)_(1A92BFA4).mkv&lt;/a&gt; </code></pre> <p>I found a tutorial that auto adds nofollow to externals link <a href="http://smartwebworker.com/485-automatic-nofollow-external-links-wordpress/" rel="nofollow">http://smartwebworker.com/485-automatic-nofollow-external-links-wordpress/</a> but it only applies to post content and not custom field. Anyone know a way to make it work with custom fields?</p>
[ { "answer_id": 180452, "author": "Ituk", "author_id": 68680, "author_profile": "https://wordpress.stackexchange.com/users/68680", "pm_score": 2, "selected": true, "text": "<p>This is something you cannot change in the field it self, but in the template file. \nCopy and paste here the template file where this option is outputted. </p>\n\n<p>Another way will be to add a javascript snippet to you <code>head</code>, if you have such option in you template.</p>\n\n<p>Comment here and we'll see what the best solution is.</p>\n\n<p>Update:</p>\n\n<p>I think best solution for you is to use 2 different custom fields - one for the url (call it Links, but put only the url and not the full html link) and one for the link title (call it Links_title, and put just the text you want to be linked).\nThen put this code in your template to output it:</p>\n\n<pre><code> &lt;a href=\"&lt;?php echo( get_post_meta( $post-&gt;ID, \"Links\", true ) ); ?&gt;\" title=\" &lt;?php echo( get_post_meta( $post-&gt;ID, \"Links_title\", true ) ); ?&gt;\" rel=\"nofollow\"&gt;\n &lt;?php echo( get_post_meta( $post-&gt;ID, \"Links_title\", true ) ); ?&gt;\n &lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 180466, "author": "ahmetertem", "author_id": 58801, "author_profile": "https://wordpress.stackexchange.com/users/58801", "pm_score": 0, "selected": false, "text": "<p>(I can't comment for being 50- reputation)\nI didn't understand your problem well. Choose or tell us; </p>\n\n<p>1) Your post content have links and you want to add nofollow to links in custom fields which already used in content</p>\n\n<p>2) You're writing your custom field's value already but just want to add nofollow.</p>\n\n<p>or tell us your scenario</p>\n\n<p><strong>Update</strong></p>\n\n<pre><code>&lt;a href=\"&lt;?php echo( get_post_meta( $post-&gt;ID, \"Links\", true ) ); ?&gt;\" rel=\"nofollow\"&gt;\n &lt;?php echo( get_post_meta( $post-&gt;ID, \"Links\", true ) ); ?&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p>is this what you need ?</p>\n" } ]
2015/03/07
[ "https://wordpress.stackexchange.com/questions/180450", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17971/" ]
I have a custom field that contains links in them and I want to auto add nofollow to those links in that custom field only. How can I do this? Example custom field value: ``` <a href="http://www.uploadable.ch/file/PnvbZ2k8B4ku/[Raizel]_Medaka_Box_01v2_(BD_720p_AAC)_(1A92BFA4).mkv">[Raizel]_Medaka_Box_01v2_(BD_720p_AAC)_(1A92BFA4).mkv</a> ``` I found a tutorial that auto adds nofollow to externals link <http://smartwebworker.com/485-automatic-nofollow-external-links-wordpress/> but it only applies to post content and not custom field. Anyone know a way to make it work with custom fields?
This is something you cannot change in the field it self, but in the template file. Copy and paste here the template file where this option is outputted. Another way will be to add a javascript snippet to you `head`, if you have such option in you template. Comment here and we'll see what the best solution is. Update: I think best solution for you is to use 2 different custom fields - one for the url (call it Links, but put only the url and not the full html link) and one for the link title (call it Links\_title, and put just the text you want to be linked). Then put this code in your template to output it: ``` <a href="<?php echo( get_post_meta( $post->ID, "Links", true ) ); ?>" title=" <?php echo( get_post_meta( $post->ID, "Links_title", true ) ); ?>" rel="nofollow"> <?php echo( get_post_meta( $post->ID, "Links_title", true ) ); ?> </a> ```
180,496
<p>I'm trying to get <code>WP_Query</code> to display ALL posts in an array but only ones with status published are showing:</p> <pre><code>global $wp_query; $ids = array(130, 132); $args = array( 'post_status' =&gt; array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'), // 'post_status' =&gt; 'any', // same output 'post__in' =&gt; $ids, 'post_type' =&gt; 'alpha' ); $q = new WP_Query($args); foreach ($q-&gt;posts as $post) { echo $post-&gt;id; } </code></pre> <p>However this displays post id's regardless of their status:</p> <pre><code>// post status foreach ($ids as $id) { echo get_post_status($id); } </code></pre> <p>This is fresh install of the Bones theme with no plugins. How do I display all posts in the array regardless of status? I must be missing something in the codex...</p>
[ { "answer_id": 291420, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 0, "selected": false, "text": "<p>Please try like this:</p>\n\n<pre><code>&lt;?php\n\nglobal $wp_query;\n\n$ids = array(130,132);\n$args = array(\n 'post_status' =&gt; array( \n 'publish', \n 'pending', \n 'draft', \n 'auto-draft', \n 'future', \n 'private', \n 'inherit', \n ),\n 'post__in' =&gt; $ids, \n 'post_type' =&gt; 'alpha'\n );\n$the_query = new WP_Query( $args );\n\nif ( $the_query-&gt;have_posts() ){\n while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n echo get_the_ID();\n endwhile;\n}\n\nwp_reset_postdata();\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 291458, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 1, "selected": false, "text": "<p>You can just <code>'post_status' =&gt; 'any'</code>.</p>\n<p>Here is the completed code.</p>\n<pre><code> global $wp_query;\n\n $ids = array(130,132);\n $args = array(\n 'post_status' =&gt; 'any', \n // 'post_status' =&gt; 'any', // same output\n 'post__in' =&gt; $ids, \n 'post_type' =&gt; 'alpha' \n );\n\n $q = new WP_Query($args);\n\n foreach ($q-&gt;posts as $post) {\n echo $post-&gt;id;\n\n }\n</code></pre>\n<p>Official docs on <code>post_status</code> option\n<a href=\"https://developer.wordpress.org/reference/classes/wp_query/#status-parameters\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/#status-parameters</a></p>\n" } ]
2015/03/07
[ "https://wordpress.stackexchange.com/questions/180496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18726/" ]
I'm trying to get `WP_Query` to display ALL posts in an array but only ones with status published are showing: ``` global $wp_query; $ids = array(130, 132); $args = array( 'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'), // 'post_status' => 'any', // same output 'post__in' => $ids, 'post_type' => 'alpha' ); $q = new WP_Query($args); foreach ($q->posts as $post) { echo $post->id; } ``` However this displays post id's regardless of their status: ``` // post status foreach ($ids as $id) { echo get_post_status($id); } ``` This is fresh install of the Bones theme with no plugins. How do I display all posts in the array regardless of status? I must be missing something in the codex...
You can just `'post_status' => 'any'`. Here is the completed code. ``` global $wp_query; $ids = array(130,132); $args = array( 'post_status' => 'any', // 'post_status' => 'any', // same output 'post__in' => $ids, 'post_type' => 'alpha' ); $q = new WP_Query($args); foreach ($q->posts as $post) { echo $post->id; } ``` Official docs on `post_status` option <https://developer.wordpress.org/reference/classes/wp_query/#status-parameters>
180,517
<p>I am working on a child theme of the WordPress Twenty Ten theme. I have several pages in WordPress (About page, Testimonials page, Contact page, etc.). I want to only echo the page content (the actual about/testimonials/contact page written content and images BUT NOT the page title). I know I can echo just the page title with:</p> <pre><code>&lt;?php single_post_title(); // echos About OR Testimonials OR Contact depending on the page selected ?&gt; </code></pre> <p>But I cannot find a WordPress function to echo only the page content without the page title? I tried:</p> <pre><code>&lt;?php get_template_part( 'content', 'page' ); ?&gt; </code></pre> <p>But it doesn't output anything.</p>
[ { "answer_id": 180520, "author": "Jason Murray", "author_id": 68194, "author_profile": "https://wordpress.stackexchange.com/users/68194", "pm_score": 0, "selected": false, "text": "<pre><code>the_content();\n</code></pre>\n\n<p>I think this is what you're looking for?</p>\n" }, { "answer_id": 180522, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You can make use of <code>the_page_content()</code> <strong>outside</strong> the loop to display only the content of the page where <code>the_page_content()</code> is supported by the following function</p>\n\n<pre><code>function the_page_content() {\n global $post;\n\n $content = '';\n if ( is_page() ) {\n $content .= apply_filters( 'the_content', $post-&gt;post_content );\n }\n echo $content;\n}\n</code></pre>\n\n<p>Inside the loop you can just use <code>the_content();</code> </p>\n" } ]
2015/03/08
[ "https://wordpress.stackexchange.com/questions/180517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25121/" ]
I am working on a child theme of the WordPress Twenty Ten theme. I have several pages in WordPress (About page, Testimonials page, Contact page, etc.). I want to only echo the page content (the actual about/testimonials/contact page written content and images BUT NOT the page title). I know I can echo just the page title with: ``` <?php single_post_title(); // echos About OR Testimonials OR Contact depending on the page selected ?> ``` But I cannot find a WordPress function to echo only the page content without the page title? I tried: ``` <?php get_template_part( 'content', 'page' ); ?> ``` But it doesn't output anything.
You can make use of `the_page_content()` **outside** the loop to display only the content of the page where `the_page_content()` is supported by the following function ``` function the_page_content() { global $post; $content = ''; if ( is_page() ) { $content .= apply_filters( 'the_content', $post->post_content ); } echo $content; } ``` Inside the loop you can just use `the_content();`
180,545
<p>UPDATE: I'm going to update this one up at the top, because the solution I've found was with a differing filter hook. I'm going to look again at reply_link-specific hooks now that I better understand how to use them, but the solution to the main problem turned out to be easy once I found the right one: 'thread_comments_depth_max', which sets the default highest maximum depth to be set in Admin/Settings/Discussion. </p> <p>Rather than explain it in detail, I'll link you to my github on the freshly minted plug-in.</p> <p><a href="https://github.com/CKMacLeod/WordPress-Nested-Comments-Unbound" rel="nofollow">https://github.com/CKMacLeod/WordPress-Nested-Comments-Unbound</a></p> <p>For now, the rest of this question is overall obsolete, though kind of a record of alternative ways of achieving the same thing with greater difficulty and less general applicability.</p> <hr> <p>Since 4.1, WordPress has made the filter "comment_reply_link_args" available, apparently (?) with the intention of letting us intercept and modify particular options normally set in the admin panel as they apply to comment reply links, while leaving everything else intact.</p> <p>Though there are many aspects of the reply link that one might want to modify via alteration of the "args," the one that prompted this investigation on my part was max_depth, so I'll use it as my prime example. </p> <p>When a nested comment thread reaches its maximum depth, the default functionality is for the comment reply link to disappear, but, on a comment thread with an active discussion at maximum_depth, continued conversation can be much easier to continue if the reply link continues to appear at the bottom of every comment - or alternatively, though a more complex implementation, at the bottom only of the thread - as if the comment thread at max-depth becomes a simple columnar/chronological thread.</p> <p>The first alternative is easy to achieve via a hack of comments_template.php (linked below), deleting two lines: </p> <pre><code>if ( 0 == $args['depth'] || $args['max_depth'] &lt;= $args['depth'] ) { return; } </code></pre> <p>However, since one of course does not want to hack WordPress core, the more common, preferred way to accomplish this end would be via theme or child-theme files and application of a callback comments function. Given how many different customized comment forms there are in different themes, this option might be preferable. However, if all you wanted to do was offer the "infinite replies" option for any theme or design using common WP functions, then the preferred method would be, if I am not mistaken, to filter the above <code>$args</code> where they hook up with comment reply link function(s).</p> <p>In order to achieve the desired effect, or the simple version of it, a theme modification that works with an elaborate custom callback function is:</p> <pre><code>comment_reply_link( array_merge( $args,array( ‘depth’ =&gt; $depth, ‘max_depth’ =&gt; $args[‘max_depth’] + 1, ) ) ); </code></pre> <p>I am copying everything except for the +1 modification as found to work applied to an actual theme's callback function. I am not completely sure about how all of the variables are declared, since, in my attempts to render the above as a filtering function used in a different theme, I continually ran into missing argument and argument not array errors. </p> <p>Leaving off more complicated attempts to correct those errors, in a simple world the following would work:</p> <pre><code>function infinite_replies() { $comment_reply_link_args = array( ‘max_depth’ =&gt; $args[‘max_depth’] + 1 ); return $comment_reply_link_args; } add_filter('comment_reply_link_args','infinite_replies', $comment, $post); </code></pre> <p>It does succeed in obliterating the reply link altogether - but nothing more. But at least it doesn't produce error messages... so I guess that's something.</p> <p>I hope that the solution to this problem will point to ways to achieve other, more complex, potentially theme-independent comment thread modifications. </p> <p>For reference, the basic documentation on comment_reply_link_args is here - <a href="http://wpseek.com/hook/comment_reply_link_args/" rel="nofollow">http://wpseek.com/hook/comment_reply_link_args/</a> - and points directly to the relevant portion of comment-template.php. </p>
[ { "answer_id": 180520, "author": "Jason Murray", "author_id": 68194, "author_profile": "https://wordpress.stackexchange.com/users/68194", "pm_score": 0, "selected": false, "text": "<pre><code>the_content();\n</code></pre>\n\n<p>I think this is what you're looking for?</p>\n" }, { "answer_id": 180522, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You can make use of <code>the_page_content()</code> <strong>outside</strong> the loop to display only the content of the page where <code>the_page_content()</code> is supported by the following function</p>\n\n<pre><code>function the_page_content() {\n global $post;\n\n $content = '';\n if ( is_page() ) {\n $content .= apply_filters( 'the_content', $post-&gt;post_content );\n }\n echo $content;\n}\n</code></pre>\n\n<p>Inside the loop you can just use <code>the_content();</code> </p>\n" } ]
2015/03/08
[ "https://wordpress.stackexchange.com/questions/180545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35923/" ]
UPDATE: I'm going to update this one up at the top, because the solution I've found was with a differing filter hook. I'm going to look again at reply\_link-specific hooks now that I better understand how to use them, but the solution to the main problem turned out to be easy once I found the right one: 'thread\_comments\_depth\_max', which sets the default highest maximum depth to be set in Admin/Settings/Discussion. Rather than explain it in detail, I'll link you to my github on the freshly minted plug-in. <https://github.com/CKMacLeod/WordPress-Nested-Comments-Unbound> For now, the rest of this question is overall obsolete, though kind of a record of alternative ways of achieving the same thing with greater difficulty and less general applicability. --- Since 4.1, WordPress has made the filter "comment\_reply\_link\_args" available, apparently (?) with the intention of letting us intercept and modify particular options normally set in the admin panel as they apply to comment reply links, while leaving everything else intact. Though there are many aspects of the reply link that one might want to modify via alteration of the "args," the one that prompted this investigation on my part was max\_depth, so I'll use it as my prime example. When a nested comment thread reaches its maximum depth, the default functionality is for the comment reply link to disappear, but, on a comment thread with an active discussion at maximum\_depth, continued conversation can be much easier to continue if the reply link continues to appear at the bottom of every comment - or alternatively, though a more complex implementation, at the bottom only of the thread - as if the comment thread at max-depth becomes a simple columnar/chronological thread. The first alternative is easy to achieve via a hack of comments\_template.php (linked below), deleting two lines: ``` if ( 0 == $args['depth'] || $args['max_depth'] <= $args['depth'] ) { return; } ``` However, since one of course does not want to hack WordPress core, the more common, preferred way to accomplish this end would be via theme or child-theme files and application of a callback comments function. Given how many different customized comment forms there are in different themes, this option might be preferable. However, if all you wanted to do was offer the "infinite replies" option for any theme or design using common WP functions, then the preferred method would be, if I am not mistaken, to filter the above `$args` where they hook up with comment reply link function(s). In order to achieve the desired effect, or the simple version of it, a theme modification that works with an elaborate custom callback function is: ``` comment_reply_link( array_merge( $args,array( ‘depth’ => $depth, ‘max_depth’ => $args[‘max_depth’] + 1, ) ) ); ``` I am copying everything except for the +1 modification as found to work applied to an actual theme's callback function. I am not completely sure about how all of the variables are declared, since, in my attempts to render the above as a filtering function used in a different theme, I continually ran into missing argument and argument not array errors. Leaving off more complicated attempts to correct those errors, in a simple world the following would work: ``` function infinite_replies() { $comment_reply_link_args = array( ‘max_depth’ => $args[‘max_depth’] + 1 ); return $comment_reply_link_args; } add_filter('comment_reply_link_args','infinite_replies', $comment, $post); ``` It does succeed in obliterating the reply link altogether - but nothing more. But at least it doesn't produce error messages... so I guess that's something. I hope that the solution to this problem will point to ways to achieve other, more complex, potentially theme-independent comment thread modifications. For reference, the basic documentation on comment\_reply\_link\_args is here - <http://wpseek.com/hook/comment_reply_link_args/> - and points directly to the relevant portion of comment-template.php.
You can make use of `the_page_content()` **outside** the loop to display only the content of the page where `the_page_content()` is supported by the following function ``` function the_page_content() { global $post; $content = ''; if ( is_page() ) { $content .= apply_filters( 'the_content', $post->post_content ); } echo $content; } ``` Inside the loop you can just use `the_content();`
180,576
<p>I want to display in page the latest post content from a category.</p> <p>For example, the category <code>foo</code> has the following posts:</p> <ul> <li><ol> <li>Hello World</li> </ol></li> <li><ol start="2"> <li>Hello Mars</li> </ol></li> <li><ol start="3"> <li>Foo bar</li> </ol></li> </ul> <p>Considering <em>Foo Bar</em> the latest article from <em>foo</em> category, its content should be rendered in a page:</p> <pre><code>&lt;title&gt; &lt;content&gt; </code></pre> <p>Where <code>&lt;title&gt;</code> is <em>Foo bar</em> and <code>&lt;content&gt;</code> is the post content.</p> <p>How can I do this?</p> <hr> <p>I'm struggling to implement the <a href="https://wordpress.stackexchange.com/users/31545/pieter-goosen">@Pieter</a>'s answer. I added these lines in <code>functions.php</code>:</p> <pre><code>function latest_post() { $args = array( 'posts_per_page' =&gt; 1, // we need only the latest post, so get that post only 'cat' =&gt; '4' // Use the category id, can also replace with category_name which uses category slug ); $str = ""; $posts = get_posts($args); foreach($posts as $post): $str = $str."&lt;h2&gt;".$post-&gt;title."&lt;/h2&gt;"; $str = $str."&lt;p class='post-content-custom'&gt;".$post-&gt;content."&lt;/p&gt;"; endforeach; return $str; } add_shortcode('latest_post', 'latest_post'); </code></pre> <p>In the page I do:</p> <pre><code>[latest_post] </code></pre> <p>However, no error appears, but the post content doesn't appear.</p>
[ { "answer_id": 180577, "author": "Jorge Y. C. Rodriguez", "author_id": 35073, "author_profile": "https://wordpress.stackexchange.com/users/35073", "pm_score": -1, "selected": false, "text": "<p>You can do something like this:::</p>\n\n<pre><code> $args = array(\n 'post_type' =&gt; '__post_type__',\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC'\n\n );\n\n$posts = get_posts($args);\nforeach($posts as $post):\n echo $post-&gt;ID;\n echo $post-&gt;title;\n echo $post-&gt;content;\nendforeach;\n</code></pre>\n" }, { "answer_id": 180579, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>You can make use of <code>WP_Query</code> to call the lastest post from the category and display it. Have a look at the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"noreferrer\">category parameters</a>. By default, <code>WP_Query</code> uses <code>post</code> as the post type and orders post by post date, so we can exclude that from the query. If you need something else, you can just define them in you arguments</p>\n\n<p>You can basically try something like this</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 1, // we need only the latest post, so get that post only\n 'cat' =&gt; 'ID OF THE CATEGORY', // Use the category id, can also replace with category_name which uses category slug\n //'category_name' =&gt; 'SLUG OF FOO CATEGORY,\n);\n$q = new WP_Query( $args);\n\nif ( $q-&gt;have_posts() ) {\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post(); \n //Your template tags and markup like:\n the_title();\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>This should provide you with a base, you can modify, customize and use it as you like. If you are unsure of the parameters and usage, check out the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\"><code>WP_Query</code> codex page</a> for assistance</p>\n\n<h2>EDIT</h2>\n\n<p>I'm really not sure why you decided to reinvent the wheel and to go with <code>get_posts</code> where as I have showed you a working example of how to use <code>WP_Query</code>. Your use of <code>get_posts</code> in conjuction with the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"noreferrer\"><code>WP_Post</code></a> properties is completely wrong</p>\n\n<ul>\n<li><p>The <code>WP_Post</code> properties is unfiltered, so the output from this is totally unfiltered and will not look the same as the output from the template tags like <code>the_title()</code> or <code>the_content()</code>. You have to use the appropriate filters on those properties</p></li>\n<li><p><code>title</code> and <code>content</code> is invalid properties of <code>WP_POST</code>. The other answer is completely wrong. It is <code>post_title</code> and <code>post_content</code></p></li>\n<li><p>You can make use of the template tags as normal by just using <code>setup_postdata( $post );</code> and then just using <code>wp_reset_postdata()</code> afterwards</p></li>\n</ul>\n\n<p>You can try the following</p>\n\n<pre><code>function latest_post() { \n $args = array(\n 'posts_per_page' =&gt; 1, // we need only the latest post, so get that post only\n 'cat' =&gt; '4' // Use the category id, can also replace with category_name which uses category slug\n );\n\n $str = \"\";\n $posts = get_posts($args);\n\n foreach($posts as $post):\n $str = $str.\"&lt;h2&gt;\". apply_filters( 'the_title', $post-&gt;post_title) .\"&lt;/h2&gt;\";\n $str = $str.\"&lt;p class='post-content-custom'&gt;\". apply_filters( 'the_content', $post-&gt;post_content ) .\"&lt;/p&gt;\";\n endforeach;\n\n return $str;\n}\n\nadd_shortcode('latest_post', 'latest_post');\n</code></pre>\n" } ]
2015/03/09
[ "https://wordpress.stackexchange.com/questions/180576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44849/" ]
I want to display in page the latest post content from a category. For example, the category `foo` has the following posts: * 1. Hello World * 2. Hello Mars * 3. Foo bar Considering *Foo Bar* the latest article from *foo* category, its content should be rendered in a page: ``` <title> <content> ``` Where `<title>` is *Foo bar* and `<content>` is the post content. How can I do this? --- I'm struggling to implement the [@Pieter](https://wordpress.stackexchange.com/users/31545/pieter-goosen)'s answer. I added these lines in `functions.php`: ``` function latest_post() { $args = array( 'posts_per_page' => 1, // we need only the latest post, so get that post only 'cat' => '4' // Use the category id, can also replace with category_name which uses category slug ); $str = ""; $posts = get_posts($args); foreach($posts as $post): $str = $str."<h2>".$post->title."</h2>"; $str = $str."<p class='post-content-custom'>".$post->content."</p>"; endforeach; return $str; } add_shortcode('latest_post', 'latest_post'); ``` In the page I do: ``` [latest_post] ``` However, no error appears, but the post content doesn't appear.
You can make use of `WP_Query` to call the lastest post from the category and display it. Have a look at the [category parameters](http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters). By default, `WP_Query` uses `post` as the post type and orders post by post date, so we can exclude that from the query. If you need something else, you can just define them in you arguments You can basically try something like this ``` $args = array( 'posts_per_page' => 1, // we need only the latest post, so get that post only 'cat' => 'ID OF THE CATEGORY', // Use the category id, can also replace with category_name which uses category slug //'category_name' => 'SLUG OF FOO CATEGORY, ); $q = new WP_Query( $args); if ( $q->have_posts() ) { while ( $q->have_posts() ) { $q->the_post(); //Your template tags and markup like: the_title(); } wp_reset_postdata(); } ``` This should provide you with a base, you can modify, customize and use it as you like. If you are unsure of the parameters and usage, check out the [`WP_Query` codex page](http://codex.wordpress.org/Class_Reference/WP_Query) for assistance EDIT ---- I'm really not sure why you decided to reinvent the wheel and to go with `get_posts` where as I have showed you a working example of how to use `WP_Query`. Your use of `get_posts` in conjuction with the [`WP_Post`](http://codex.wordpress.org/Class_Reference/WP_Post) properties is completely wrong * The `WP_Post` properties is unfiltered, so the output from this is totally unfiltered and will not look the same as the output from the template tags like `the_title()` or `the_content()`. You have to use the appropriate filters on those properties * `title` and `content` is invalid properties of `WP_POST`. The other answer is completely wrong. It is `post_title` and `post_content` * You can make use of the template tags as normal by just using `setup_postdata( $post );` and then just using `wp_reset_postdata()` afterwards You can try the following ``` function latest_post() { $args = array( 'posts_per_page' => 1, // we need only the latest post, so get that post only 'cat' => '4' // Use the category id, can also replace with category_name which uses category slug ); $str = ""; $posts = get_posts($args); foreach($posts as $post): $str = $str."<h2>". apply_filters( 'the_title', $post->post_title) ."</h2>"; $str = $str."<p class='post-content-custom'>". apply_filters( 'the_content', $post->post_content ) ."</p>"; endforeach; return $str; } add_shortcode('latest_post', 'latest_post'); ```
180,589
<p>I have a custom post type <code>product</code>. Visitors can search <code>products</code> with many filters. They can set the <code>color</code>, the <code>size</code>, the <code>price</code>, etc. The details of the product are stored with <em>Advanced Custom Fields (ACF)</em>.</p> <p>My solution was a <code>WP_Query</code> with <code>meta_queries</code>. All <code>WP_Meta_Queries</code> are in <code>AND</code>-relations.</p> <p>My problem is: If the visitor creates more filter for the product, the query will always be slower. I think the <code>INNER JOIN</code>s on <code>wp_postmeta</code> are the problem. I have six <code>INNER JOIN</code>s on this table.</p> <p>Is there a solution for this problem?</p>
[ { "answer_id": 180591, "author": "LeMike", "author_id": 42974, "author_profile": "https://wordpress.stackexchange.com/users/42974", "pm_score": 3, "selected": false, "text": "<p>You might need a 180° solution here ;)\nThink about the problem once more and try this:</p>\n\n<blockquote>\n <p>As a visitor I can filter by color and size.</p>\n</blockquote>\n\n<p>So your solution might be:</p>\n\n<pre><code>...\nJOIN ... (A)\n... (B)\n... (C)\nWHERE (A.meta_key = 'color' AND A.meta_value = 'red')\nOR (B.meta_key = 'color' AND B.meta_value = 'blue')\n...\nAND (C.meta_key = 'size' AND C.meta_value = 1)\n...\n</code></pre>\n\n<p>But actually you can drop some joins using <code>IN</code>:</p>\n\n<pre><code>JOIN ... (A)\n... (B)\nWHERE (A.meta_key = 'color' AND A.meta_value IN ('red', 'yellow'))\nAND (B.meta_key = 'size' AND B.meta_value IN (1, 2, 3))\n</code></pre>\n\n<p>So start using \"IN\" for comparing values <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\">like in the manual</a>:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'my_custom_post_type',\n 'meta_key' =&gt; 'age',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'age',\n 'value' =&gt; array( 3, 4 ),\n 'compare' =&gt; 'IN',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>You can even start guessing and have it with only one or no join at all:</p>\n\n<pre><code>WHERE meta_key IN ('color', 'size')\n AND meta_value IN ('red', 'blue', 123, 45)\n</code></pre>\n\n<p>This would be fast but might end up in lots of false positives.</p>\n" }, { "answer_id": 180628, "author": "Hari Om Gupta", "author_id": 68792, "author_profile": "https://wordpress.stackexchange.com/users/68792", "pm_score": -1, "selected": false, "text": "<p>if you are using woocommerce, you can simply use the <a href=\"https://wordpress.org/plugins/woocommerce-ajax-filters/\" rel=\"nofollow\">advanced ajax product filters</a></p>\n\n<p>This plugin will help you with all post meta.</p>\n" } ]
2015/03/09
[ "https://wordpress.stackexchange.com/questions/180589", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65647/" ]
I have a custom post type `product`. Visitors can search `products` with many filters. They can set the `color`, the `size`, the `price`, etc. The details of the product are stored with *Advanced Custom Fields (ACF)*. My solution was a `WP_Query` with `meta_queries`. All `WP_Meta_Queries` are in `AND`-relations. My problem is: If the visitor creates more filter for the product, the query will always be slower. I think the `INNER JOIN`s on `wp_postmeta` are the problem. I have six `INNER JOIN`s on this table. Is there a solution for this problem?
You might need a 180° solution here ;) Think about the problem once more and try this: > > As a visitor I can filter by color and size. > > > So your solution might be: ``` ... JOIN ... (A) ... (B) ... (C) WHERE (A.meta_key = 'color' AND A.meta_value = 'red') OR (B.meta_key = 'color' AND B.meta_value = 'blue') ... AND (C.meta_key = 'size' AND C.meta_value = 1) ... ``` But actually you can drop some joins using `IN`: ``` JOIN ... (A) ... (B) WHERE (A.meta_key = 'color' AND A.meta_value IN ('red', 'yellow')) AND (B.meta_key = 'size' AND B.meta_value IN (1, 2, 3)) ``` So start using "IN" for comparing values [like in the manual](http://codex.wordpress.org/Class_Reference/WP_Query): ``` $args = array( 'post_type' => 'my_custom_post_type', 'meta_key' => 'age', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'age', 'value' => array( 3, 4 ), 'compare' => 'IN', ), ), ); $query = new WP_Query( $args ); ``` You can even start guessing and have it with only one or no join at all: ``` WHERE meta_key IN ('color', 'size') AND meta_value IN ('red', 'blue', 123, 45) ``` This would be fast but might end up in lots of false positives.
180,590
<p>Currently I am using WooCommerce for WordPress and trying to add custom fields for Variations Product. After did some researches, I found some code and tried to modify it.</p> <p>This is my full code : <a href="https://gist.github.com/alphadc/da163cc95cfd1cede34a" rel="nofollow">https://gist.github.com/alphadc/da163cc95cfd1cede34a</a></p> <pre><code>add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 ); add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' ); add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 ); add_action( 'woocommerce_process_product_meta_variable-subscription' , 'save_variable_fields' , 10 , 1 ) ; function variable_fields( $loop, $variation_data ) {?&gt; &lt;tr&gt; &lt;td&gt; &lt;?php woocommerce_wp_textarea_input( array( 'id' =&gt; '_weightdesc['.$loop.']', 'label' =&gt; __( 'Weight Description', 'woocommerce' ), 'placeholder' =&gt; '', 'description' =&gt; __( 'Enter the custom value here.', 'woocommerce' ), 'value' =&gt; $variation_data['_weightdesc'][0], ) ); ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } function variable_fields_js()?&gt; &lt;tr&gt; &lt;td&gt; &lt;?php woocommerce_wp_textarea_input( array( 'id' =&gt; '_weightdesc[ + loop + ]', 'label' =&gt; __( 'My Textarea', 'woocommerce' ), 'placeholder' =&gt; '', 'description' =&gt; __( 'Enter the custom value here.', 'woocommerce' ), 'value' =&gt; $variation_data['_weightdesc'][0], ) ); ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } function save_variable_fields( $post_id ) { if (isset( $_POST['variable_sku'] ) ) : $variable_sku = $_POST['variable_sku']; $variable_post_id = $_POST['variable_post_id']; // Textarea $_weightdesc = $_POST['_weightdesc']; for ( $i = 0; $i &lt; sizeof( $variable_sku ); $i++ ) : $variation_id = (int) $variable_post_id[$i]; if ( isset( $_weightdesc[$i] ) ) { update_post_meta( $variation_id, '_weightdesc', stripslashes( $_weightdesc[$i] ) ); } endfor; endif; } </code></pre> <p>The field is showing on my backend, but when I tried to save the value, it's not working. I tried to modified it too, but still not working.</p> <p>I found this code from several sources one of this came from : <a href="http://www.remicorson.com/woocommerce-custom-fields-for-variations/#comment-14159" rel="nofollow">http://www.remicorson.com/woocommerce-custom-fields-for-variations/#comment-14159</a></p> <p>I think this is because of the update of WooCommerce (I am using 2.3.5).</p> <p>Can someone help me please?</p>
[ { "answer_id": 180967, "author": "Irwan", "author_id": 58082, "author_profile": "https://wordpress.stackexchange.com/users/58082", "pm_score": 4, "selected": true, "text": "<p>Okay, based on answers on link above (where I got the old code and there are people that help to answered), I put the modification code for my website. I tried it and it's working like charm.</p>\n\n<p>Change:</p>\n\n<pre><code>add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 );\n</code></pre>\n\n<p>Into :</p>\n\n<pre><code>add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 );\n</code></pre>\n\n<p>And change : </p>\n\n<pre><code>'value' =&gt; $variation_data['_weightdesc'][0],\n</code></pre>\n\n<p>Into :</p>\n\n<pre><code>'value' =&gt; get_post_meta($variation-&gt;ID, '_weightdesc', true)\n</code></pre>\n" }, { "answer_id": 198833, "author": "CᴴᵁᴮᴮʸNᴵᴺᴶᴬ", "author_id": 28557, "author_profile": "https://wordpress.stackexchange.com/users/28557", "pm_score": 2, "selected": false, "text": "<p>I know this post is old, but to keep this question updated:</p>\n\n<h2>As of WooCommerce 2.4.4</h2>\n\n<p><code>woocommerce_process_product_meta_variable</code> no longer works, and it must be changed to <code>woocommerce_save_product_variation</code></p>\n\n<p>So,</p>\n\n<p>Change:</p>\n\n<pre><code>add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 );\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>add_action( 'woocommerce_save_product_variation', 'save_variable_fields', 10, 1 );\n</code></pre>\n" }, { "answer_id": 330432, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": -1, "selected": false, "text": "<pre><code>function variation_settings_fields( $loop, $variation_data, $variation ) {\n\n // Text Field\n woocommerce_wp_text_input(\n array(\n 'id' =&gt; '_text_field[' . $variation-&gt;ID . ']',\n 'label' =&gt; __( 'My Text Field', 'woocommerce' ),\n 'placeholder' =&gt; '',\n 'desc_tip' =&gt; 'true',\n 'description' =&gt; __( 'Enter the custom value here.', 'woocommerce' ),\n 'value' =&gt; get_post_meta( $variation-&gt;ID, '_text_field', true )\n )\n );\n\n}\nadd_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );\n\nfunction save_variation_settings_fields( $post_id ) {\n\n // Text Field\n $text_field = $_POST['_text_field'][ $post_id ];\n if ( ! empty( $text_field ) ) {\n update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );\n }\n}\n\nadd_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );\n</code></pre>\n" } ]
2015/03/09
[ "https://wordpress.stackexchange.com/questions/180590", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58082/" ]
Currently I am using WooCommerce for WordPress and trying to add custom fields for Variations Product. After did some researches, I found some code and tried to modify it. This is my full code : <https://gist.github.com/alphadc/da163cc95cfd1cede34a> ``` add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 ); add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' ); add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 ); add_action( 'woocommerce_process_product_meta_variable-subscription' , 'save_variable_fields' , 10 , 1 ) ; function variable_fields( $loop, $variation_data ) {?> <tr> <td> <?php woocommerce_wp_textarea_input( array( 'id' => '_weightdesc['.$loop.']', 'label' => __( 'Weight Description', 'woocommerce' ), 'placeholder' => '', 'description' => __( 'Enter the custom value here.', 'woocommerce' ), 'value' => $variation_data['_weightdesc'][0], ) ); ?> </td> </tr> <?php } function variable_fields_js()?> <tr> <td> <?php woocommerce_wp_textarea_input( array( 'id' => '_weightdesc[ + loop + ]', 'label' => __( 'My Textarea', 'woocommerce' ), 'placeholder' => '', 'description' => __( 'Enter the custom value here.', 'woocommerce' ), 'value' => $variation_data['_weightdesc'][0], ) ); ?> </td> </tr> <?php } function save_variable_fields( $post_id ) { if (isset( $_POST['variable_sku'] ) ) : $variable_sku = $_POST['variable_sku']; $variable_post_id = $_POST['variable_post_id']; // Textarea $_weightdesc = $_POST['_weightdesc']; for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) : $variation_id = (int) $variable_post_id[$i]; if ( isset( $_weightdesc[$i] ) ) { update_post_meta( $variation_id, '_weightdesc', stripslashes( $_weightdesc[$i] ) ); } endfor; endif; } ``` The field is showing on my backend, but when I tried to save the value, it's not working. I tried to modified it too, but still not working. I found this code from several sources one of this came from : <http://www.remicorson.com/woocommerce-custom-fields-for-variations/#comment-14159> I think this is because of the update of WooCommerce (I am using 2.3.5). Can someone help me please?
Okay, based on answers on link above (where I got the old code and there are people that help to answered), I put the modification code for my website. I tried it and it's working like charm. Change: ``` add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 ); ``` Into : ``` add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 ); ``` And change : ``` 'value' => $variation_data['_weightdesc'][0], ``` Into : ``` 'value' => get_post_meta($variation->ID, '_weightdesc', true) ```
180,593
<p>I am using <code>&lt;?php wp_get_attachment_thumb_url( $attachment_id ); ?&gt;</code> to get the url of a thumbnail for a post in Wordpress. However I would like to retrieve the URL of a specific size image. So for example when displaying the post thunmbnail normally you can specify a size, like: <code>&lt;?php the_post_thumbnail( $size, $attr ); ?&gt;</code>. Is it possible to do the same with wp_get_attachment_thumb_url.</p> <p>Something like: <code>&lt;?php wp_get_attachment_thumb_url( $attachment_id, $size ); ?&gt;</code>?</p>
[ { "answer_id": 180967, "author": "Irwan", "author_id": 58082, "author_profile": "https://wordpress.stackexchange.com/users/58082", "pm_score": 4, "selected": true, "text": "<p>Okay, based on answers on link above (where I got the old code and there are people that help to answered), I put the modification code for my website. I tried it and it's working like charm.</p>\n\n<p>Change:</p>\n\n<pre><code>add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 );\n</code></pre>\n\n<p>Into :</p>\n\n<pre><code>add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 );\n</code></pre>\n\n<p>And change : </p>\n\n<pre><code>'value' =&gt; $variation_data['_weightdesc'][0],\n</code></pre>\n\n<p>Into :</p>\n\n<pre><code>'value' =&gt; get_post_meta($variation-&gt;ID, '_weightdesc', true)\n</code></pre>\n" }, { "answer_id": 198833, "author": "CᴴᵁᴮᴮʸNᴵᴺᴶᴬ", "author_id": 28557, "author_profile": "https://wordpress.stackexchange.com/users/28557", "pm_score": 2, "selected": false, "text": "<p>I know this post is old, but to keep this question updated:</p>\n\n<h2>As of WooCommerce 2.4.4</h2>\n\n<p><code>woocommerce_process_product_meta_variable</code> no longer works, and it must be changed to <code>woocommerce_save_product_variation</code></p>\n\n<p>So,</p>\n\n<p>Change:</p>\n\n<pre><code>add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 );\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>add_action( 'woocommerce_save_product_variation', 'save_variable_fields', 10, 1 );\n</code></pre>\n" }, { "answer_id": 330432, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": -1, "selected": false, "text": "<pre><code>function variation_settings_fields( $loop, $variation_data, $variation ) {\n\n // Text Field\n woocommerce_wp_text_input(\n array(\n 'id' =&gt; '_text_field[' . $variation-&gt;ID . ']',\n 'label' =&gt; __( 'My Text Field', 'woocommerce' ),\n 'placeholder' =&gt; '',\n 'desc_tip' =&gt; 'true',\n 'description' =&gt; __( 'Enter the custom value here.', 'woocommerce' ),\n 'value' =&gt; get_post_meta( $variation-&gt;ID, '_text_field', true )\n )\n );\n\n}\nadd_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );\n\nfunction save_variation_settings_fields( $post_id ) {\n\n // Text Field\n $text_field = $_POST['_text_field'][ $post_id ];\n if ( ! empty( $text_field ) ) {\n update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );\n }\n}\n\nadd_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );\n</code></pre>\n" } ]
2015/03/09
[ "https://wordpress.stackexchange.com/questions/180593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47334/" ]
I am using `<?php wp_get_attachment_thumb_url( $attachment_id ); ?>` to get the url of a thumbnail for a post in Wordpress. However I would like to retrieve the URL of a specific size image. So for example when displaying the post thunmbnail normally you can specify a size, like: `<?php the_post_thumbnail( $size, $attr ); ?>`. Is it possible to do the same with wp\_get\_attachment\_thumb\_url. Something like: `<?php wp_get_attachment_thumb_url( $attachment_id, $size ); ?>`?
Okay, based on answers on link above (where I got the old code and there are people that help to answered), I put the modification code for my website. I tried it and it's working like charm. Change: ``` add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 ); ``` Into : ``` add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 ); ``` And change : ``` 'value' => $variation_data['_weightdesc'][0], ``` Into : ``` 'value' => get_post_meta($variation->ID, '_weightdesc', true) ```
180,671
<p>i created a custom post type and also some taxonomy to be able to perform sorting on the display list.</p> <p>It is all working well on my local testing installation but as soon as i put on the production website (where there is some other plugins etc installed compared to my local), then the sorting is not working anymore, any idea ?</p> <p>Here some part of the plugin code related to my taxonomy and custom post type :</p> <pre><code>add_action('init', 'students_init'); function students_init(){ $labels = array( 'name' =&gt; 'Students', 'singular_name' =&gt; 'Student', 'add_new' =&gt; 'Add a student', 'add_new_item' =&gt; 'Add a new student', 'edit_item' =&gt; 'Edit a student', 'new_item' =&gt; 'New student', 'view_item' =&gt; 'See the student', 'search_items' =&gt; 'Search a student', 'not_found' =&gt; 'No students', 'not_found_in_trash' =&gt; 'No students in the trash', 'parent_item_colon' =&gt; '', 'menu_name' =&gt; 'Students', ); register_post_type('student', array( 'public' =&gt; true, 'publicly_queryable' =&gt; false, 'labels' =&gt; $labels, 'menu_position' =&gt; 2, 'capability_type' =&gt; 'post', 'supports' =&gt; false, )); //add_image_size('slider', 1000, 300, true); register_taxonomy( 'activity', 'student', array( 'hierarchical' =&gt; true, 'label' =&gt; 'Activity', 'query_var' =&gt; true, 'rewrite' =&gt; true, 'show_admin_column' =&gt; true, ) ); } add_action( 'restrict_manage_posts', 'students_restrict_manage_posts' ); function students_restrict_manage_posts() { global $typenow; if ( $typenow == 'student' ) { $taxonomy = 'activity'; wp_dropdown_categories(array( 'show_option_all' =&gt; 'Voir toutes les catégories', 'taxonomy' =&gt; $taxonomy, 'name' =&gt; $taxonomy, 'orderby' =&gt; 'name', 'selected' =&gt; $_GET[$taxonomy], 'hierarchical' =&gt; true, 'show_count' =&gt; true, 'hide_empty' =&gt; true )); } } add_action( 'request', 'students_admin_request' ); function students_admin_request( $request ) { if ( is_admin() &amp;&amp; isset( $request['post_type'] ) &amp;&amp; $request['post_type'] == 'student' ) { $taxonomy = 'activity'; $request[$taxonomy] = get_term_by( 'id', $request[$taxonomy], $taxonomy)-&gt;slug; } return $request; } </code></pre> <p>Here what i have :</p> <p><img src="https://i.stack.imgur.com/DVGfQ.jpg" alt="enter image description here"></p> <p>here what i get when i filter :</p> <p><img src="https://i.stack.imgur.com/MLhFH.jpg" alt="enter image description here"></p> <p>Thanks a lot in advance for your help :)</p>
[ { "answer_id": 180967, "author": "Irwan", "author_id": 58082, "author_profile": "https://wordpress.stackexchange.com/users/58082", "pm_score": 4, "selected": true, "text": "<p>Okay, based on answers on link above (where I got the old code and there are people that help to answered), I put the modification code for my website. I tried it and it's working like charm.</p>\n\n<p>Change:</p>\n\n<pre><code>add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 );\n</code></pre>\n\n<p>Into :</p>\n\n<pre><code>add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 );\n</code></pre>\n\n<p>And change : </p>\n\n<pre><code>'value' =&gt; $variation_data['_weightdesc'][0],\n</code></pre>\n\n<p>Into :</p>\n\n<pre><code>'value' =&gt; get_post_meta($variation-&gt;ID, '_weightdesc', true)\n</code></pre>\n" }, { "answer_id": 198833, "author": "CᴴᵁᴮᴮʸNᴵᴺᴶᴬ", "author_id": 28557, "author_profile": "https://wordpress.stackexchange.com/users/28557", "pm_score": 2, "selected": false, "text": "<p>I know this post is old, but to keep this question updated:</p>\n\n<h2>As of WooCommerce 2.4.4</h2>\n\n<p><code>woocommerce_process_product_meta_variable</code> no longer works, and it must be changed to <code>woocommerce_save_product_variation</code></p>\n\n<p>So,</p>\n\n<p>Change:</p>\n\n<pre><code>add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 );\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>add_action( 'woocommerce_save_product_variation', 'save_variable_fields', 10, 1 );\n</code></pre>\n" }, { "answer_id": 330432, "author": "Unicco", "author_id": 52622, "author_profile": "https://wordpress.stackexchange.com/users/52622", "pm_score": -1, "selected": false, "text": "<pre><code>function variation_settings_fields( $loop, $variation_data, $variation ) {\n\n // Text Field\n woocommerce_wp_text_input(\n array(\n 'id' =&gt; '_text_field[' . $variation-&gt;ID . ']',\n 'label' =&gt; __( 'My Text Field', 'woocommerce' ),\n 'placeholder' =&gt; '',\n 'desc_tip' =&gt; 'true',\n 'description' =&gt; __( 'Enter the custom value here.', 'woocommerce' ),\n 'value' =&gt; get_post_meta( $variation-&gt;ID, '_text_field', true )\n )\n );\n\n}\nadd_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );\n\nfunction save_variation_settings_fields( $post_id ) {\n\n // Text Field\n $text_field = $_POST['_text_field'][ $post_id ];\n if ( ! empty( $text_field ) ) {\n update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );\n }\n}\n\nadd_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );\n</code></pre>\n" } ]
2015/03/10
[ "https://wordpress.stackexchange.com/questions/180671", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68814/" ]
i created a custom post type and also some taxonomy to be able to perform sorting on the display list. It is all working well on my local testing installation but as soon as i put on the production website (where there is some other plugins etc installed compared to my local), then the sorting is not working anymore, any idea ? Here some part of the plugin code related to my taxonomy and custom post type : ``` add_action('init', 'students_init'); function students_init(){ $labels = array( 'name' => 'Students', 'singular_name' => 'Student', 'add_new' => 'Add a student', 'add_new_item' => 'Add a new student', 'edit_item' => 'Edit a student', 'new_item' => 'New student', 'view_item' => 'See the student', 'search_items' => 'Search a student', 'not_found' => 'No students', 'not_found_in_trash' => 'No students in the trash', 'parent_item_colon' => '', 'menu_name' => 'Students', ); register_post_type('student', array( 'public' => true, 'publicly_queryable' => false, 'labels' => $labels, 'menu_position' => 2, 'capability_type' => 'post', 'supports' => false, )); //add_image_size('slider', 1000, 300, true); register_taxonomy( 'activity', 'student', array( 'hierarchical' => true, 'label' => 'Activity', 'query_var' => true, 'rewrite' => true, 'show_admin_column' => true, ) ); } add_action( 'restrict_manage_posts', 'students_restrict_manage_posts' ); function students_restrict_manage_posts() { global $typenow; if ( $typenow == 'student' ) { $taxonomy = 'activity'; wp_dropdown_categories(array( 'show_option_all' => 'Voir toutes les catégories', 'taxonomy' => $taxonomy, 'name' => $taxonomy, 'orderby' => 'name', 'selected' => $_GET[$taxonomy], 'hierarchical' => true, 'show_count' => true, 'hide_empty' => true )); } } add_action( 'request', 'students_admin_request' ); function students_admin_request( $request ) { if ( is_admin() && isset( $request['post_type'] ) && $request['post_type'] == 'student' ) { $taxonomy = 'activity'; $request[$taxonomy] = get_term_by( 'id', $request[$taxonomy], $taxonomy)->slug; } return $request; } ``` Here what i have : ![enter image description here](https://i.stack.imgur.com/DVGfQ.jpg) here what i get when i filter : ![enter image description here](https://i.stack.imgur.com/MLhFH.jpg) Thanks a lot in advance for your help :)
Okay, based on answers on link above (where I got the old code and there are people that help to answered), I put the modification code for my website. I tried it and it's working like charm. Change: ``` add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 ); ``` Into : ``` add_action( 'woocommerce_variation_options', 'variable_fields', 10, 3 ); ``` And change : ``` 'value' => $variation_data['_weightdesc'][0], ``` Into : ``` 'value' => get_post_meta($variation->ID, '_weightdesc', true) ```
180,678
<p>My client is using these two plugins: - All in One Buttons - Genesis Design Palette</p> <p>If you check this example page <a href="http://bsc.mustor.com/testing-buttons/" rel="nofollow">http://bsc.mustor.com/testing-buttons/</a> you will see that time text on the button is maroon and red (hover). It is supposed to be white.</p> <p>The style sheet inserted by Genesis Design Palette is overriding All In One Buttons AND the theme styles. This is despite All In One Buttons style.css and the theme's style.css both referring specifically to the element in question aio-orange. Genesis Design Palette's style overrides with a more general style applied to entry content.</p> <p>How can I give the correct styles precedence in this situation?</p> <p>Thanks</p>
[ { "answer_id": 180690, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 1, "selected": false, "text": "<p>On the definition of the aio-orange button in the all-in-one-buttons/css/display.css?ver=4.1.1 add !important after the #FFF.</p>\n\n<p>The color is overwritten because you load the AIO styles first and later some other style that overrides button styles or what not. With !important you can tell the browser to use that one even though it's not the latest definition.</p>\n\n<p>So it would be like</p>\n\n<pre><code>a.aio-orange, a.aio-orange:link, a.aio-orange:hover, a.aio-orange:visited, a.aio-orange:active, a.aio-orange:focus {\ncolor: #FFF !important;\n}\n</code></pre>\n\n<p>Or something like that.</p>\n" }, { "answer_id": 180722, "author": "Sean Grant", "author_id": 67105, "author_profile": "https://wordpress.stackexchange.com/users/67105", "pm_score": 0, "selected": false, "text": "<p>Ideally one of those plugins would have an option to load their CSS file last or first. You'd want the AIO Button to load last.</p>\n\n<p>Otherwise you could edit the CSS class with the color you want as '!important' like jimihenrik suggested, although that's not recommended for long term solutions.</p>\n\n<p>Or you could overwrite the offending CSS style from Genesis Design Palette's style by being even more 'specific' then they are with your CSS rule. </p>\n\n<p>Example of being more specific:\nTheir code says:</p>\n\n<pre><code>body.gppro-custom .content &gt; .entry .entry-content a { color: maroon; }\n</code></pre>\n\n<p>Your code can overwrite it by being more specific with the CSS rule:</p>\n\n<pre><code>body .content &gt; .entry .entry-content .aio-button-center a { color: white; }\n</code></pre>\n\n<p>This will change all .aio-button-center links within the .entry-content to white.\nYou can place this in any CSS file of yours... like your custom CSS for the theme.</p>\n\n<p>For more info read this fun article on CSS Specificity: <a href=\"https://css-tricks.com/specifics-on-css-specificity/\" rel=\"nofollow\">https://css-tricks.com/specifics-on-css-specificity/</a></p>\n" } ]
2015/03/10
[ "https://wordpress.stackexchange.com/questions/180678", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64780/" ]
My client is using these two plugins: - All in One Buttons - Genesis Design Palette If you check this example page <http://bsc.mustor.com/testing-buttons/> you will see that time text on the button is maroon and red (hover). It is supposed to be white. The style sheet inserted by Genesis Design Palette is overriding All In One Buttons AND the theme styles. This is despite All In One Buttons style.css and the theme's style.css both referring specifically to the element in question aio-orange. Genesis Design Palette's style overrides with a more general style applied to entry content. How can I give the correct styles precedence in this situation? Thanks
On the definition of the aio-orange button in the all-in-one-buttons/css/display.css?ver=4.1.1 add !important after the #FFF. The color is overwritten because you load the AIO styles first and later some other style that overrides button styles or what not. With !important you can tell the browser to use that one even though it's not the latest definition. So it would be like ``` a.aio-orange, a.aio-orange:link, a.aio-orange:hover, a.aio-orange:visited, a.aio-orange:active, a.aio-orange:focus { color: #FFF !important; } ``` Or something like that.
180,727
<p>I am developing a game, and I am planning that, I will have partners, so they can run a game like mine.</p> <p>For this, I developed a plugin, with some classes, and functions, to handle the game requests.</p> <p>Because, this plugin is totally unusable for all the wordpress users, I want to send to my partners this plugin in an email in zipped format, but I want them to make able to upgrade plugin, if they need.</p> <p>So, is it possible, to store the plugin on my own server, and force plugin to check updates from my site, not from the wp plugins directory?</p>
[ { "answer_id": 180729, "author": "Ben Cole", "author_id": 32532, "author_profile": "https://wordpress.stackexchange.com/users/32532", "pm_score": 2, "selected": false, "text": "<p>Yes, it is possible to host your own plugin and have the plugin check for updates from your server. You need to put some custom code in your plugin to tell it to check with your server for updates. There are some frameworks to help you do that, try these:</p>\n\n<ul>\n<li><p><a href=\"https://github.com/YahnisElsts/plugin-update-checker\" rel=\"nofollow\">Plugin Update Checker</a></p></li>\n<li><p><a href=\"https://github.com/radishconcepts/WordPress-GitHub-Plugin-Updater\" rel=\"nofollow\">Github Plugin Updater</a></p></li>\n</ul>\n" }, { "answer_id": 180736, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": false, "text": "<p>All Credit to the following post goes to <a href=\"http://tutsplus.com/authors/abid-omar\" rel=\"noreferrer\">Abid</a> <a href=\"https://github.com/omarabid\" rel=\"noreferrer\">Omar</a>. The full tutorial can be found on Tuts+: <a href=\"http://code.tutsplus.com/tutorials/a-guide-to-the-wordpress-http-api-automatic-plugin-updates--wp-25181\" rel=\"noreferrer\">A Guide to the WordPress HTTP API: Automatic Plugin Updates</a></p>\n\n<p><a href=\"https://github.com/omarabid/Self-Hosted-WordPress-Plugin-repository\" rel=\"noreferrer\">View Plugin On Github</a></p>\n\n<hr>\n\n<p>The gist is to create a new class which will post an external file ( API ) and return plugin to download if it's out of date. The below assumes you're creating a plugin using the following code ( not in <code>functions.php</code> or <code>mu-plugins</code> directory ).</p>\n\n<ol>\n<li><code>wp_autoupdate.php</code> will be an external file ( in your plugin ) holding the Auto Update class defined below</li>\n<li><code>update.php</code> is an external \"remote\" file used to check for update, creates the API.</li>\n</ol>\n\n<p>The below will be our initial setup.</p>\n\n<pre><code>add_action( 'init', 'wptuts_activate_au' );\nfunction wptuts_activate_au()\n{\n require_once ('wp_autoupdate.php'); // File which contains the Class below\n $wptuts_plugin_current_version = '1.0';\n $wptuts_plugin_remote_path = 'http://localhost/update.php';\n $wptuts_plugin_slug = plugin_basename(__FILE__);\n new wp_auto_update( $wptuts_plugin_current_version, $wptuts_plugin_remote_path, $wptuts_plugin_slug );\n}\n</code></pre>\n\n<p><strong>Autoupdate Class - <code>wp_autoupdate.php</code></strong></p>\n\n<pre><code>class wp_auto_update\n{\n /**\n * The plugin current version\n * @var string\n */\n public $current_version;\n\n /**\n * The plugin remote update path\n * @var string\n */\n public $update_path;\n\n /**\n * Plugin Slug (plugin_directory/plugin_file.php)\n * @var string\n */\n public $plugin_slug;\n\n /**\n * Plugin name (plugin_file)\n * @var string\n */\n public $slug;\n\n /**\n * Initialize a new instance of the WordPress Auto-Update class\n * @param string $current_version\n * @param string $update_path\n * @param string $plugin_slug\n */\n function __construct( $current_version, $update_path, $plugin_slug )\n {\n // Set the class public variables\n $this-&gt;current_version = $current_version;\n $this-&gt;update_path = $update_path;\n $this-&gt;plugin_slug = $plugin_slug;\n list ($t1, $t2) = explode('/', $plugin_slug);\n $this-&gt;slug = str_replace( '.php', '', $t2 );\n\n // define the alternative API for updating checking\n add_filter( 'pre_set_site_transient_update_plugins', array( &amp;$this, 'check_update' ) );\n\n // Define the alternative response for information checking\n add_filter('plugins_api', array(&amp;$this, 'check_info'), 10, 3);\n }\n\n /**\n * Add our self-hosted autoupdate plugin to the filter transient\n *\n * @param $transient\n * @return object $ transient\n */\n public function check_update( $transient )\n {\n if( empty( $transient-&gt;checked ) ) {\n return $transient;\n }\n\n // Get the remote version\n $remote_version = $this-&gt;getRemote_version();\n\n // If a newer version is available, add the update\n if ( version_compare( $this-&gt;current_version, $remote_version, '&lt;' ) ) {\n $obj = new stdClass();\n $obj-&gt;slug = $this-&gt;slug;\n $obj-&gt;new_version = $remote_version;\n $obj-&gt;url = $this-&gt;update_path;\n $obj-&gt;package = $this-&gt;update_path;\n $transient-&gt;response[$this-&gt;plugin_slug] = $obj;\n }\n var_dump( $transient );\n return $transient;\n }\n\n /**\n * Add our self-hosted description to the filter\n *\n * @param boolean $false\n * @param array $action\n * @param object $arg\n * @return bool|object\n */\n public function check_info( $false, $action, $arg )\n {\n if( $arg-&gt;slug === $this-&gt;slug ) {\n $information = $this-&gt;getRemote_information();\n return $information;\n }\n return false;\n }\n\n /**\n * Return the remote version\n * @return string $remote_version\n */\n public function getRemote_version()\n {\n $request = wp_remote_post( $this-&gt;update_path, array( 'body' =&gt; array( 'action' =&gt; 'version' ) ) );\n if( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {\n return $request['body'];\n }\n return false;\n }\n\n /**\n * Get information about the remote version\n * @return bool|object\n */\n public function getRemote_information()\n {\n $request = wp_remote_post( $this-&gt;update_path, array( 'body' =&gt; array( 'action' =&gt; 'info' ) ) );\n if( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200) {\n return unserialize( $request['body'] );\n }\n return false;\n }\n\n /**\n * Return the status of the plugin licensing\n * @return boolean $remote_license\n */\n public function getRemote_license()\n {\n $request = wp_remote_post( $this-&gt;update_path, array( 'body' =&gt; array( 'action' =&gt; 'license' ) ) );\n if( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {\n return $request['body'];\n }\n return false;\n }\n}\n</code></pre>\n\n<p><strong>Remote ( External ) Update API - <code>update.php</code></strong></p>\n\n<pre><code>if( isset( $_POST['action'] ) ) {\n switch( $_POST['action'] ) {\n case 'version':\n echo '1.1';\n break;\n\n case 'info':\n $obj = new stdClass();\n $obj-&gt;slug = 'plugin.php';\n $obj-&gt;plugin_name = 'plugin.php';\n $obj-&gt;new_version = '1.1';\n $obj-&gt;requires = '3.0';\n $obj-&gt;tested = '3.3.1';\n $obj-&gt;downloaded = 12540;\n $obj-&gt;last_updated = '2012-01-12';\n $obj-&gt;sections = array(\n 'description' =&gt; 'The new version of the Auto-Update plugin',\n 'another_section' =&gt; 'This is another section',\n 'changelog' =&gt; 'Some new features'\n );\n $obj-&gt;download_link = 'http://localhost/update.php';\n echo serialize( $obj );\n\n case 'license':\n echo 'false';\n break;\n }\n} else {\n header( 'Cache-Control: public' );\n header( 'Content-Description: File Transfer' );\n header( 'Content-Type: application/zip' );\n readfile( 'update.zip' );\n}\n</code></pre>\n\n<hr>\n\n<p><code>update.php</code> will keep the most up-to-date information on your plugin. Using the <code>init</code> function you would pass the currently <em>installed</em> version so that it can post it to <code>update.php</code> and check against the current it has. There's some room for improvement on the code to make it more streamlined but I used this to do exactly ( sorta ) what you're trying to do so it's a good jumping point. </p>\n" }, { "answer_id": 410844, "author": "Jesse Nickles", "author_id": 152624, "author_profile": "https://wordpress.stackexchange.com/users/152624", "pm_score": 1, "selected": false, "text": "<p>I have returned to this &quot;problem&quot; several times over the years, and a few of the projects on GitHub shared in the answers here are fantastic, although some of them appear dead now. There have also been some WooCommerce extensions that have attempted to solve this problem while also providing a billing solution, but they were kinda janky and difficult to maintain in my experience.</p>\n<p>However one other fantastic solution is Andy Fragen's <a href=\"https://github.com/afragen/git-updater\" rel=\"nofollow noreferrer\">Git Updater</a>. Instead of having to host your plugin ZIP files on your (unreliable) self-hosted server and/or hack your plugins and themes to add more files and dependencies etc, you simply add a simple one-line &quot;header&quot; inside your <code>style.css</code> file for WordPress themes or inside your <code>plugin.php</code> file for plugins. Literally, that's all that's required.</p>\n<p>Here's an example:</p>\n<p><a href=\"https://github.com/littlebizzy/hovercraft/blob/master/style.css\" rel=\"nofollow noreferrer\">https://github.com/littlebizzy/hovercraft/blob/master/style.css</a></p>\n<pre><code>GitHub Theme URI: littlebizzy/hovercraft\n</code></pre>\n<p>Andy's approach is one of the cleanest I've seen, and saved me tons of time and headache trying to find a simple solution for updating my WordPress extensions.</p>\n<p>It works out-of-the-box for public repos, and has support for API keys for private repos. So you could literally just have like a PayPal or Patreon subscription where customers pay for access to whichever code they want and then you provide them the API key to those private repos on GitHub or GitLab, etc. You don't need to manage any ZIP files or billing whatsover.</p>\n<p>And the implementation only takes around 30 seconds for most projects.</p>\n" } ]
2015/03/10
[ "https://wordpress.stackexchange.com/questions/180727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68847/" ]
I am developing a game, and I am planning that, I will have partners, so they can run a game like mine. For this, I developed a plugin, with some classes, and functions, to handle the game requests. Because, this plugin is totally unusable for all the wordpress users, I want to send to my partners this plugin in an email in zipped format, but I want them to make able to upgrade plugin, if they need. So, is it possible, to store the plugin on my own server, and force plugin to check updates from my site, not from the wp plugins directory?
All Credit to the following post goes to [Abid](http://tutsplus.com/authors/abid-omar) [Omar](https://github.com/omarabid). The full tutorial can be found on Tuts+: [A Guide to the WordPress HTTP API: Automatic Plugin Updates](http://code.tutsplus.com/tutorials/a-guide-to-the-wordpress-http-api-automatic-plugin-updates--wp-25181) [View Plugin On Github](https://github.com/omarabid/Self-Hosted-WordPress-Plugin-repository) --- The gist is to create a new class which will post an external file ( API ) and return plugin to download if it's out of date. The below assumes you're creating a plugin using the following code ( not in `functions.php` or `mu-plugins` directory ). 1. `wp_autoupdate.php` will be an external file ( in your plugin ) holding the Auto Update class defined below 2. `update.php` is an external "remote" file used to check for update, creates the API. The below will be our initial setup. ``` add_action( 'init', 'wptuts_activate_au' ); function wptuts_activate_au() { require_once ('wp_autoupdate.php'); // File which contains the Class below $wptuts_plugin_current_version = '1.0'; $wptuts_plugin_remote_path = 'http://localhost/update.php'; $wptuts_plugin_slug = plugin_basename(__FILE__); new wp_auto_update( $wptuts_plugin_current_version, $wptuts_plugin_remote_path, $wptuts_plugin_slug ); } ``` **Autoupdate Class - `wp_autoupdate.php`** ``` class wp_auto_update { /** * The plugin current version * @var string */ public $current_version; /** * The plugin remote update path * @var string */ public $update_path; /** * Plugin Slug (plugin_directory/plugin_file.php) * @var string */ public $plugin_slug; /** * Plugin name (plugin_file) * @var string */ public $slug; /** * Initialize a new instance of the WordPress Auto-Update class * @param string $current_version * @param string $update_path * @param string $plugin_slug */ function __construct( $current_version, $update_path, $plugin_slug ) { // Set the class public variables $this->current_version = $current_version; $this->update_path = $update_path; $this->plugin_slug = $plugin_slug; list ($t1, $t2) = explode('/', $plugin_slug); $this->slug = str_replace( '.php', '', $t2 ); // define the alternative API for updating checking add_filter( 'pre_set_site_transient_update_plugins', array( &$this, 'check_update' ) ); // Define the alternative response for information checking add_filter('plugins_api', array(&$this, 'check_info'), 10, 3); } /** * Add our self-hosted autoupdate plugin to the filter transient * * @param $transient * @return object $ transient */ public function check_update( $transient ) { if( empty( $transient->checked ) ) { return $transient; } // Get the remote version $remote_version = $this->getRemote_version(); // If a newer version is available, add the update if ( version_compare( $this->current_version, $remote_version, '<' ) ) { $obj = new stdClass(); $obj->slug = $this->slug; $obj->new_version = $remote_version; $obj->url = $this->update_path; $obj->package = $this->update_path; $transient->response[$this->plugin_slug] = $obj; } var_dump( $transient ); return $transient; } /** * Add our self-hosted description to the filter * * @param boolean $false * @param array $action * @param object $arg * @return bool|object */ public function check_info( $false, $action, $arg ) { if( $arg->slug === $this->slug ) { $information = $this->getRemote_information(); return $information; } return false; } /** * Return the remote version * @return string $remote_version */ public function getRemote_version() { $request = wp_remote_post( $this->update_path, array( 'body' => array( 'action' => 'version' ) ) ); if( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) { return $request['body']; } return false; } /** * Get information about the remote version * @return bool|object */ public function getRemote_information() { $request = wp_remote_post( $this->update_path, array( 'body' => array( 'action' => 'info' ) ) ); if( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200) { return unserialize( $request['body'] ); } return false; } /** * Return the status of the plugin licensing * @return boolean $remote_license */ public function getRemote_license() { $request = wp_remote_post( $this->update_path, array( 'body' => array( 'action' => 'license' ) ) ); if( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) { return $request['body']; } return false; } } ``` **Remote ( External ) Update API - `update.php`** ``` if( isset( $_POST['action'] ) ) { switch( $_POST['action'] ) { case 'version': echo '1.1'; break; case 'info': $obj = new stdClass(); $obj->slug = 'plugin.php'; $obj->plugin_name = 'plugin.php'; $obj->new_version = '1.1'; $obj->requires = '3.0'; $obj->tested = '3.3.1'; $obj->downloaded = 12540; $obj->last_updated = '2012-01-12'; $obj->sections = array( 'description' => 'The new version of the Auto-Update plugin', 'another_section' => 'This is another section', 'changelog' => 'Some new features' ); $obj->download_link = 'http://localhost/update.php'; echo serialize( $obj ); case 'license': echo 'false'; break; } } else { header( 'Cache-Control: public' ); header( 'Content-Description: File Transfer' ); header( 'Content-Type: application/zip' ); readfile( 'update.zip' ); } ``` --- `update.php` will keep the most up-to-date information on your plugin. Using the `init` function you would pass the currently *installed* version so that it can post it to `update.php` and check against the current it has. There's some room for improvement on the code to make it more streamlined but I used this to do exactly ( sorta ) what you're trying to do so it's a good jumping point.
180,762
<p>Ok, I've got this simple code for a simple plugin which prepends post titles with the word TESTING.. I'm really unclear how the parameter works here. I understand how parameters work in PHP, but nothing has been passed inside this parameter for WordPress to know the variable is the title.. if that makes sense?? Don't get how it's working.</p> <p>I'm still fairly crap at WordPress development - I always seem to start, get stuck and don't get very far.</p> <pre><code>add_filter('the_title', 'cm_title'); /** * Modify the title prepending the article title with the word 'TESTING' */ function cm_title($text) { return 'TESTING &amp;nbsp;' . $text; } </code></pre>
[ { "answer_id": 180768, "author": "Sean Grant", "author_id": 67105, "author_profile": "https://wordpress.stackexchange.com/users/67105", "pm_score": 2, "selected": true, "text": "<p>Let's see if we can break it down so it's easy to understand.</p>\n\n<p>You have a PHP function named 'cm_title':</p>\n\n<pre><code>function cm_title($text) {\n return 'TESTING &amp;nbsp;' . $text;\n}\n</code></pre>\n\n<p>It only does 1 thing. It takes what it is given, '$text', and returns that $text with the words 'Testing ' prepended to it.</p>\n\n<p>How does WordPress know what '$text' is?</p>\n\n<p>It knows/assigns data to the $text parameter because of this WP filter:</p>\n\n<pre><code>add_filter('the_title', 'cm_title');\n</code></pre>\n\n<p>This filter is checked by WP when it is building 'the_title'. So just before WP spits out 'the_title' it checks to see if there is a filter to use. In this case we are telling WP to apply this filter (the function 'cm_title') before spitting out the title.</p>\n\n<p>All that to say WP sends what it has so far for 'the_title' (ie. 'This is a Post About me') and runs it through this filter before spitting it out. </p>\n\n<p><strong>So in this case, 'This is a Post About me' is the data in the $text parameter in the cm_title function.</strong></p>\n\n<p>Your end result becomes 'TESTING This is a Post About me'.</p>\n\n<p>Does that help clear it up?</p>\n" }, { "answer_id": 180772, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>WordPress uses <em>hooks</em> to help developers do what they need to do in a relatively easy way. Some of these hooks are <code>apply_filter()</code> and <code>do_action()</code> which is defined by WordPress. Let's see exactly what happens when we call <code>the_title()</code> all the way up until it hits the hook you defined. </p>\n\n<pre><code>&lt;?php the_title(); ?&gt;\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\">Developer Resources - <code>the_title()</code></a></p>\n\n<pre><code>function the_title($before = '', $after = '', $echo = true) {\n $title = get_the_title();\n\n if ( strlen($title) == 0 )\n return;\n\n $title = $before . $title . $after;\n\n if ( $echo )\n echo $title;\n else\n return $title;\n}\n</code></pre>\n\n<p>Right at the top it calls <code>get_the_title()</code> which is where we'll find our filter. Let's take a look at that:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\">Developer Resources - <code>get_the_title()</code></a></p>\n\n<pre><code>function get_the_title( $post = 0 ) {\n $post = get_post( $post );\n\n $title = isset( $post-&gt;post_title ) ? $post-&gt;post_title : '';\n $id = isset( $post-&gt;ID ) ? $post-&gt;ID : 0;\n\n if ( ! is_admin() ) {\n if ( ! empty( $post-&gt;post_password ) ) {\n\n /**\n * Filter the text prepended to the post title for protected posts.\n *\n * The filter is only applied on the front end.\n *\n * @since 2.8.0\n *\n * @param string $prepend Text displayed before the post title.\n * Default 'Protected: %s'.\n * @param WP_Post $post Current post object.\n */\n $protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ), $post );\n $title = sprintf( $protected_title_format, $title );\n } else if ( isset( $post-&gt;post_status ) &amp;&amp; 'private' == $post-&gt;post_status ) {\n\n /**\n * Filter the text prepended to the post title of private posts.\n *\n * The filter is only applied on the front end.\n *\n * @since 2.8.0\n *\n * @param string $prepend Text displayed before the post title.\n * Default 'Private: %s'.\n * @param WP_Post $post Current post object.\n */\n $private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ), $post );\n $title = sprintf( $private_title_format, $title );\n }\n }\n\n /**\n * Filter the post title.\n *\n * @since 0.71\n *\n * @param string $title The post title.\n * @param int $id The post ID.\n */\n return apply_filters( 'the_title', $title, $id );\n}\n</code></pre>\n\n<p>You'll notice directly at the bottom of the function it calls <code>apply_filters()</code> and passes in a <code>function_name</code> as <strong>string</strong>, <code>$title</code> as <strong>string</strong> and <code>$id</code> as <strong>int</strong> then returns whatever <code>apply_fitlers()</code> returns, which is <em>your hook</em>. Let's take a look at <code>apply_filters()</code>:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow noreferrer\">Developer Resources - <code>apply_filters()</code></a></p>\n\n<pre><code>function apply_filters( $tag, $value ) {\n global $wp_filter, $merged_filters, $wp_current_filter;\n\n $args = array();\n\n // Do 'all' actions first.\n if ( isset($wp_filter['all']) ) {\n $wp_current_filter[] = $tag;\n $args = func_get_args();\n _wp_call_all_hook($args);\n }\n\n if ( !isset($wp_filter[$tag]) ) {\n if ( isset($wp_filter['all']) )\n array_pop($wp_current_filter);\n return $value;\n }\n\n if ( !isset($wp_filter['all']) )\n $wp_current_filter[] = $tag;\n\n // Sort.\n if ( !isset( $merged_filters[ $tag ] ) ) {\n ksort($wp_filter[$tag]);\n $merged_filters[ $tag ] = true;\n }\n\n reset( $wp_filter[ $tag ] );\n\n if ( empty($args) )\n $args = func_get_args();\n\n do {\n foreach( (array) current($wp_filter[$tag]) as $the_ )\n if ( !is_null($the_['function']) ){\n $args[1] = $value;\n $value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));\n }\n\n } while ( next($wp_filter[$tag]) !== false );\n\n array_pop( $wp_current_filter );\n\n return $value;\n}\n</code></pre>\n\n<p>It looks complex but before we jump into that let's get to the most important piece of this function, <code>$wp_filter</code>. Now this little bugger contains ALL the filters added by both you AND WordPress. You can print it out right underneath your <code>wp_head()</code> to see the full list. It looks something like this ( tons more, I just picked <code>the_title</code> since it's on topic! )</p>\n\n<pre><code>[the_title] =&gt; Array\n (\n [10] =&gt; Array\n (\n [wptexturize] =&gt; Array\n (\n [function] =&gt; wptexturize\n [accepted_args] =&gt; 1\n )\n\n [convert_chars] =&gt; Array\n (\n [function] =&gt; convert_chars\n [accepted_args] =&gt; 1\n )\n\n [trim] =&gt; Array\n (\n [function] =&gt; trim\n [accepted_args] =&gt; 1\n )\n\n )\n\n [11] =&gt; Array\n (\n [capital_P_dangit] =&gt; Array\n (\n [function] =&gt; capital_P_dangit\n [accepted_args] =&gt; 1\n )\n\n )\n\n )\n</code></pre>\n\n<p>So it's a multi-dimensional array of filters, indexed by <strong>tag</strong>, then by <strong>priority</strong> and finally by <strong>function name</strong>. Pretty neat I think! The filter you added, since you didn't pass a priority, is defaulted to index <em>10</em> and would be added right underneath <code>trim</code> and then further indexed by function name <code>cm_title</code>.</p>\n\n<p>Let's go back a little bit. If we look at the end of <code>get_the_title()</code> function above we see it passing <strong>three</strong> variables into the <code>apply_filters</code> function but as we can clearly see it only accepts <strong>two</strong> parameters! I had to look into this a little bit and it looks like this little function, <code>func_get_args()</code> we see littered inside <code>apply_filters()</code> actually will grab anything and everything passed to it. <a href=\"https://stackoverflow.com/questions/5268079/what-is-the-good-example-of-using-func-get-arg-in-php\">Here's an example</a>, the <a href=\"http://codepad.org/mRdBN5MK\" rel=\"nofollow noreferrer\">Codepen</a> is also nice. Now even though anything can be passed, if we look back up at our mutlidimensional array there's an <code>accepted_args</code> parameters so technically, you kinda can't even though it <em>allows</em> you to. </p>\n\n<p><em>PHEW</em></p>\n\n<p>Finally, it loops through each one of these filters using the <code>$wp_filters</code> array:</p>\n\n<pre><code>do {\n foreach( (array) current($wp_filter[$tag]) as $the_ )\n if ( !is_null($the_['function']) ){\n $args[1] = $value;\n $value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));\n }\n\n} while ( next($wp_filter[$tag]) !== false );\n</code></pre>\n\n<p>So, let's bring it all together!</p>\n\n<ul>\n<li><code>the_title()</code> calls <code>get_the_title()</code></li>\n<li><code>get_the_title()</code> returns <code>apply_filters()</code>, passing in: 'the_title' (function name), <code>$title</code> (string post title), <code>$id</code> (int post id).</li>\n<li><code>apply_filters()</code> looks through a global array that holds all filters added then runs them passing in the information that was passed to it ( <code>$title</code>, and <code>$id</code> ).</li>\n</ul>\n\n<hr>\n\n<p>The function you call <code>add_filter</code> actually adds your function name, priority, and args to the global <code>$wp_filters</code> array. You can see that below:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">Developer Resources - <code>add_filter()</code></a></p>\n\n<pre><code>function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {\n global $wp_filter, $merged_filters;\n\n $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);\n $wp_filter[$tag][$priority][$idx] = array('function' =&gt; $function_to_add, 'accepted_args' =&gt; $accepted_args);\n unset( $merged_filters[ $tag ] );\n return true;\n}\n</code></pre>\n\n<p>Really, this is called before <code>the_title()</code> ever gets called. Your functions are loaded with <code>wp_head()</code> and thus any filters you add through plugins or <code>functions.php</code> will also be added to this global array.</p>\n\n<hr>\n\n<p>That was lengthy but hopefully it makes a little more sense now, if you have any questions ask in the comments!</p>\n" } ]
2015/03/10
[ "https://wordpress.stackexchange.com/questions/180762", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68865/" ]
Ok, I've got this simple code for a simple plugin which prepends post titles with the word TESTING.. I'm really unclear how the parameter works here. I understand how parameters work in PHP, but nothing has been passed inside this parameter for WordPress to know the variable is the title.. if that makes sense?? Don't get how it's working. I'm still fairly crap at WordPress development - I always seem to start, get stuck and don't get very far. ``` add_filter('the_title', 'cm_title'); /** * Modify the title prepending the article title with the word 'TESTING' */ function cm_title($text) { return 'TESTING &nbsp;' . $text; } ```
Let's see if we can break it down so it's easy to understand. You have a PHP function named 'cm\_title': ``` function cm_title($text) { return 'TESTING &nbsp;' . $text; } ``` It only does 1 thing. It takes what it is given, '$text', and returns that $text with the words 'Testing ' prepended to it. How does WordPress know what '$text' is? It knows/assigns data to the $text parameter because of this WP filter: ``` add_filter('the_title', 'cm_title'); ``` This filter is checked by WP when it is building 'the\_title'. So just before WP spits out 'the\_title' it checks to see if there is a filter to use. In this case we are telling WP to apply this filter (the function 'cm\_title') before spitting out the title. All that to say WP sends what it has so far for 'the\_title' (ie. 'This is a Post About me') and runs it through this filter before spitting it out. **So in this case, 'This is a Post About me' is the data in the $text parameter in the cm\_title function.** Your end result becomes 'TESTING This is a Post About me'. Does that help clear it up?
180,838
<p>I am trying to use MAMP's built in Xip.io functionality to view a WordPress multisite installation on a local network. I have this working no problem with a WordPress single installation but am struggling with multisite. Just wondered if anyone knew what needed changing in the wp-config file to get this working using multisite as changing database entries isn't really the way forward here.</p>
[ { "answer_id": 180768, "author": "Sean Grant", "author_id": 67105, "author_profile": "https://wordpress.stackexchange.com/users/67105", "pm_score": 2, "selected": true, "text": "<p>Let's see if we can break it down so it's easy to understand.</p>\n\n<p>You have a PHP function named 'cm_title':</p>\n\n<pre><code>function cm_title($text) {\n return 'TESTING &amp;nbsp;' . $text;\n}\n</code></pre>\n\n<p>It only does 1 thing. It takes what it is given, '$text', and returns that $text with the words 'Testing ' prepended to it.</p>\n\n<p>How does WordPress know what '$text' is?</p>\n\n<p>It knows/assigns data to the $text parameter because of this WP filter:</p>\n\n<pre><code>add_filter('the_title', 'cm_title');\n</code></pre>\n\n<p>This filter is checked by WP when it is building 'the_title'. So just before WP spits out 'the_title' it checks to see if there is a filter to use. In this case we are telling WP to apply this filter (the function 'cm_title') before spitting out the title.</p>\n\n<p>All that to say WP sends what it has so far for 'the_title' (ie. 'This is a Post About me') and runs it through this filter before spitting it out. </p>\n\n<p><strong>So in this case, 'This is a Post About me' is the data in the $text parameter in the cm_title function.</strong></p>\n\n<p>Your end result becomes 'TESTING This is a Post About me'.</p>\n\n<p>Does that help clear it up?</p>\n" }, { "answer_id": 180772, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>WordPress uses <em>hooks</em> to help developers do what they need to do in a relatively easy way. Some of these hooks are <code>apply_filter()</code> and <code>do_action()</code> which is defined by WordPress. Let's see exactly what happens when we call <code>the_title()</code> all the way up until it hits the hook you defined. </p>\n\n<pre><code>&lt;?php the_title(); ?&gt;\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\">Developer Resources - <code>the_title()</code></a></p>\n\n<pre><code>function the_title($before = '', $after = '', $echo = true) {\n $title = get_the_title();\n\n if ( strlen($title) == 0 )\n return;\n\n $title = $before . $title . $after;\n\n if ( $echo )\n echo $title;\n else\n return $title;\n}\n</code></pre>\n\n<p>Right at the top it calls <code>get_the_title()</code> which is where we'll find our filter. Let's take a look at that:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow noreferrer\">Developer Resources - <code>get_the_title()</code></a></p>\n\n<pre><code>function get_the_title( $post = 0 ) {\n $post = get_post( $post );\n\n $title = isset( $post-&gt;post_title ) ? $post-&gt;post_title : '';\n $id = isset( $post-&gt;ID ) ? $post-&gt;ID : 0;\n\n if ( ! is_admin() ) {\n if ( ! empty( $post-&gt;post_password ) ) {\n\n /**\n * Filter the text prepended to the post title for protected posts.\n *\n * The filter is only applied on the front end.\n *\n * @since 2.8.0\n *\n * @param string $prepend Text displayed before the post title.\n * Default 'Protected: %s'.\n * @param WP_Post $post Current post object.\n */\n $protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ), $post );\n $title = sprintf( $protected_title_format, $title );\n } else if ( isset( $post-&gt;post_status ) &amp;&amp; 'private' == $post-&gt;post_status ) {\n\n /**\n * Filter the text prepended to the post title of private posts.\n *\n * The filter is only applied on the front end.\n *\n * @since 2.8.0\n *\n * @param string $prepend Text displayed before the post title.\n * Default 'Private: %s'.\n * @param WP_Post $post Current post object.\n */\n $private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ), $post );\n $title = sprintf( $private_title_format, $title );\n }\n }\n\n /**\n * Filter the post title.\n *\n * @since 0.71\n *\n * @param string $title The post title.\n * @param int $id The post ID.\n */\n return apply_filters( 'the_title', $title, $id );\n}\n</code></pre>\n\n<p>You'll notice directly at the bottom of the function it calls <code>apply_filters()</code> and passes in a <code>function_name</code> as <strong>string</strong>, <code>$title</code> as <strong>string</strong> and <code>$id</code> as <strong>int</strong> then returns whatever <code>apply_fitlers()</code> returns, which is <em>your hook</em>. Let's take a look at <code>apply_filters()</code>:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow noreferrer\">Developer Resources - <code>apply_filters()</code></a></p>\n\n<pre><code>function apply_filters( $tag, $value ) {\n global $wp_filter, $merged_filters, $wp_current_filter;\n\n $args = array();\n\n // Do 'all' actions first.\n if ( isset($wp_filter['all']) ) {\n $wp_current_filter[] = $tag;\n $args = func_get_args();\n _wp_call_all_hook($args);\n }\n\n if ( !isset($wp_filter[$tag]) ) {\n if ( isset($wp_filter['all']) )\n array_pop($wp_current_filter);\n return $value;\n }\n\n if ( !isset($wp_filter['all']) )\n $wp_current_filter[] = $tag;\n\n // Sort.\n if ( !isset( $merged_filters[ $tag ] ) ) {\n ksort($wp_filter[$tag]);\n $merged_filters[ $tag ] = true;\n }\n\n reset( $wp_filter[ $tag ] );\n\n if ( empty($args) )\n $args = func_get_args();\n\n do {\n foreach( (array) current($wp_filter[$tag]) as $the_ )\n if ( !is_null($the_['function']) ){\n $args[1] = $value;\n $value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));\n }\n\n } while ( next($wp_filter[$tag]) !== false );\n\n array_pop( $wp_current_filter );\n\n return $value;\n}\n</code></pre>\n\n<p>It looks complex but before we jump into that let's get to the most important piece of this function, <code>$wp_filter</code>. Now this little bugger contains ALL the filters added by both you AND WordPress. You can print it out right underneath your <code>wp_head()</code> to see the full list. It looks something like this ( tons more, I just picked <code>the_title</code> since it's on topic! )</p>\n\n<pre><code>[the_title] =&gt; Array\n (\n [10] =&gt; Array\n (\n [wptexturize] =&gt; Array\n (\n [function] =&gt; wptexturize\n [accepted_args] =&gt; 1\n )\n\n [convert_chars] =&gt; Array\n (\n [function] =&gt; convert_chars\n [accepted_args] =&gt; 1\n )\n\n [trim] =&gt; Array\n (\n [function] =&gt; trim\n [accepted_args] =&gt; 1\n )\n\n )\n\n [11] =&gt; Array\n (\n [capital_P_dangit] =&gt; Array\n (\n [function] =&gt; capital_P_dangit\n [accepted_args] =&gt; 1\n )\n\n )\n\n )\n</code></pre>\n\n<p>So it's a multi-dimensional array of filters, indexed by <strong>tag</strong>, then by <strong>priority</strong> and finally by <strong>function name</strong>. Pretty neat I think! The filter you added, since you didn't pass a priority, is defaulted to index <em>10</em> and would be added right underneath <code>trim</code> and then further indexed by function name <code>cm_title</code>.</p>\n\n<p>Let's go back a little bit. If we look at the end of <code>get_the_title()</code> function above we see it passing <strong>three</strong> variables into the <code>apply_filters</code> function but as we can clearly see it only accepts <strong>two</strong> parameters! I had to look into this a little bit and it looks like this little function, <code>func_get_args()</code> we see littered inside <code>apply_filters()</code> actually will grab anything and everything passed to it. <a href=\"https://stackoverflow.com/questions/5268079/what-is-the-good-example-of-using-func-get-arg-in-php\">Here's an example</a>, the <a href=\"http://codepad.org/mRdBN5MK\" rel=\"nofollow noreferrer\">Codepen</a> is also nice. Now even though anything can be passed, if we look back up at our mutlidimensional array there's an <code>accepted_args</code> parameters so technically, you kinda can't even though it <em>allows</em> you to. </p>\n\n<p><em>PHEW</em></p>\n\n<p>Finally, it loops through each one of these filters using the <code>$wp_filters</code> array:</p>\n\n<pre><code>do {\n foreach( (array) current($wp_filter[$tag]) as $the_ )\n if ( !is_null($the_['function']) ){\n $args[1] = $value;\n $value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));\n }\n\n} while ( next($wp_filter[$tag]) !== false );\n</code></pre>\n\n<p>So, let's bring it all together!</p>\n\n<ul>\n<li><code>the_title()</code> calls <code>get_the_title()</code></li>\n<li><code>get_the_title()</code> returns <code>apply_filters()</code>, passing in: 'the_title' (function name), <code>$title</code> (string post title), <code>$id</code> (int post id).</li>\n<li><code>apply_filters()</code> looks through a global array that holds all filters added then runs them passing in the information that was passed to it ( <code>$title</code>, and <code>$id</code> ).</li>\n</ul>\n\n<hr>\n\n<p>The function you call <code>add_filter</code> actually adds your function name, priority, and args to the global <code>$wp_filters</code> array. You can see that below:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">Developer Resources - <code>add_filter()</code></a></p>\n\n<pre><code>function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {\n global $wp_filter, $merged_filters;\n\n $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);\n $wp_filter[$tag][$priority][$idx] = array('function' =&gt; $function_to_add, 'accepted_args' =&gt; $accepted_args);\n unset( $merged_filters[ $tag ] );\n return true;\n}\n</code></pre>\n\n<p>Really, this is called before <code>the_title()</code> ever gets called. Your functions are loaded with <code>wp_head()</code> and thus any filters you add through plugins or <code>functions.php</code> will also be added to this global array.</p>\n\n<hr>\n\n<p>That was lengthy but hopefully it makes a little more sense now, if you have any questions ask in the comments!</p>\n" } ]
2015/03/11
[ "https://wordpress.stackexchange.com/questions/180838", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23406/" ]
I am trying to use MAMP's built in Xip.io functionality to view a WordPress multisite installation on a local network. I have this working no problem with a WordPress single installation but am struggling with multisite. Just wondered if anyone knew what needed changing in the wp-config file to get this working using multisite as changing database entries isn't really the way forward here.
Let's see if we can break it down so it's easy to understand. You have a PHP function named 'cm\_title': ``` function cm_title($text) { return 'TESTING &nbsp;' . $text; } ``` It only does 1 thing. It takes what it is given, '$text', and returns that $text with the words 'Testing ' prepended to it. How does WordPress know what '$text' is? It knows/assigns data to the $text parameter because of this WP filter: ``` add_filter('the_title', 'cm_title'); ``` This filter is checked by WP when it is building 'the\_title'. So just before WP spits out 'the\_title' it checks to see if there is a filter to use. In this case we are telling WP to apply this filter (the function 'cm\_title') before spitting out the title. All that to say WP sends what it has so far for 'the\_title' (ie. 'This is a Post About me') and runs it through this filter before spitting it out. **So in this case, 'This is a Post About me' is the data in the $text parameter in the cm\_title function.** Your end result becomes 'TESTING This is a Post About me'. Does that help clear it up?
180,852
<p>I am working in Wordpress, and I would like to make certain elements disappear once a user logs in. How can I do this?</p> <p>I have social icons on my page that I positioned to the center of my menu bar at the top of my website. those icons are generated by a plugin</p> <p>that is what i want to disappear </p> <p><a href="https://hughesjobs.net" rel="nofollow">https://hughesjobs.net</a></p>
[ { "answer_id": 180853, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 1, "selected": false, "text": "<p>You'll want to use a PHP if statement in combination with <a href=\"http://codex.wordpress.org/Function_Reference/is_user_logged_in\" rel=\"nofollow\"><code>is_user_logged_in</code></a></p>\n\n<p>If you're editing your header try this:</p>\n\n<pre><code>&lt;?php if (!is_user_logged_in()) { ?&gt;\n// Your social media icons code goes here\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>The exclamation point before <code>is_user_logged_in()</code> means 'is not' in PHP, so your code essentially says, \"If the user is not logged in, show the code between the brackets\".</p>\n" }, { "answer_id": 235396, "author": "Jerome D. Dizon", "author_id": 100685, "author_profile": "https://wordpress.stackexchange.com/users/100685", "pm_score": 0, "selected": false, "text": "<p>Add this to your <code>functions.php</code></p>\n\n<pre><code>function remove_social_to_logged_users() {\n if (is_user_logged_in()) {\n $remove_icons =\" &lt;style&gt;\n section#widgetizerupv91rw {\n display: none;\n }\n &lt;/style&gt; \";\n\n echo $remove_icons; \n } \n}\n\nadd_action( 'wp_head', 'remove_social_to_logged_users' );\n</code></pre>\n\n<p>I check your website and get the id of the social icons. I'm willing to help you to add this in your website if you like.</p>\n" } ]
2015/03/11
[ "https://wordpress.stackexchange.com/questions/180852", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65468/" ]
I am working in Wordpress, and I would like to make certain elements disappear once a user logs in. How can I do this? I have social icons on my page that I positioned to the center of my menu bar at the top of my website. those icons are generated by a plugin that is what i want to disappear <https://hughesjobs.net>
You'll want to use a PHP if statement in combination with [`is_user_logged_in`](http://codex.wordpress.org/Function_Reference/is_user_logged_in) If you're editing your header try this: ``` <?php if (!is_user_logged_in()) { ?> // Your social media icons code goes here <?php } ?> ``` The exclamation point before `is_user_logged_in()` means 'is not' in PHP, so your code essentially says, "If the user is not logged in, show the code between the brackets".
180,887
<p>After hours of searching and trying different functions, I've finally successfully removed the /author/ from all of our users profile URLs. So its just /username/</p> <p>However, when new users register their profile URL's all give 404's. I can fix this by going into the permalinks screen and clicking save but we register lots of users and I cannot do this for each one. </p> <p>This is the function I'm using... Any Ideas!?</p> <p>Thanks!</p> <pre><code> add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules'); function no_author_base_rewrite_rules($author_rewrite) { global $wpdb; $author_rewrite = array(); $authors = $wpdb-&gt;get_results("SELECT user_nicename AS nicename from $wpdb-&gt;users"); foreach($authors as $author) { $author_rewrite["({$author-&gt;nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&amp;paged=$matches[2]'; $author_rewrite["({$author-&gt;nicename})/?$"] = 'index.php?author_name=$matches[1]'; } return $author_rewrite; } if( !is_admin() ) { add_action('init', 'author_rewrite_so_22115103'); } function author_rewrite_so_22115103() { global $wp_rewrite; if( 'author' == $wp_rewrite-&gt;author_base ) $wp_rewrite-&gt;author_base = null; } </code></pre>
[ { "answer_id": 180897, "author": "Dave Ross", "author_id": 3851, "author_profile": "https://wordpress.stackexchange.com/users/3851", "pm_score": 0, "selected": false, "text": "<p><code>author_rewrite_rules</code> is only going to be invoked when WordPress needs to regenerate the rewrite rules. So you need to give WordPress a reason to do that. Saving on the permalinks page is one way. Another would be to hook into the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\"><code>user_register</code></a> action, which is called right after a new user is created. Inside your handler function, call <a href=\"http://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow\"><code>flush_rewrite_rules()</code></a>.</p>\n" }, { "answer_id": 190280, "author": "lucian", "author_id": 70333, "author_profile": "https://wordpress.stackexchange.com/users/70333", "pm_score": 0, "selected": false, "text": "<p>Also add this near the other similar two, in order to redirect the feeds as well:</p>\n\n<pre><code>$author_rewrite[\"({$author-&gt;nicename})/page/?([0-9]+)/?$\"] = 'index.php?author_name=$matches[1]&amp;paged=$matches[2]';\n</code></pre>\n" }, { "answer_id": 262085, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You are just doing it wrong. Adding a per user rewrite rule will just bloat the rewrite \"table\" and slow down the URL parsing process. You need to come up with a generic rewrite rule which will work for all users, or write an alternative url parsing using the 'do_parse_request filter.</p>\n\n<p>Your core problem is that your URL structure as it is now \"collides\" with the url structure of posts/categories/etc, and the best way is to just use a constant predictable prefix for your user urls maybe something like <code>/user/{user login}/...</code> otherwise, the only sane option in a site with many users is to do your own parsing.</p>\n" } ]
2015/03/11
[ "https://wordpress.stackexchange.com/questions/180887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18085/" ]
After hours of searching and trying different functions, I've finally successfully removed the /author/ from all of our users profile URLs. So its just /username/ However, when new users register their profile URL's all give 404's. I can fix this by going into the permalinks screen and clicking save but we register lots of users and I cannot do this for each one. This is the function I'm using... Any Ideas!? Thanks! ``` add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules'); function no_author_base_rewrite_rules($author_rewrite) { global $wpdb; $author_rewrite = array(); $authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users"); foreach($authors as $author) { $author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]'; $author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]'; } return $author_rewrite; } if( !is_admin() ) { add_action('init', 'author_rewrite_so_22115103'); } function author_rewrite_so_22115103() { global $wp_rewrite; if( 'author' == $wp_rewrite->author_base ) $wp_rewrite->author_base = null; } ```
You are just doing it wrong. Adding a per user rewrite rule will just bloat the rewrite "table" and slow down the URL parsing process. You need to come up with a generic rewrite rule which will work for all users, or write an alternative url parsing using the 'do\_parse\_request filter. Your core problem is that your URL structure as it is now "collides" with the url structure of posts/categories/etc, and the best way is to just use a constant predictable prefix for your user urls maybe something like `/user/{user login}/...` otherwise, the only sane option in a site with many users is to do your own parsing.
180,964
<p>I tried to use get_page_link('page-id') and get_permalink('page-id') but the error below occurred.</p> <blockquote> <p><strong>Fatal error:</strong> Call to a member function get_page_permastruct() on null in ...</p> </blockquote> <p>How can I get a page url knowing only its ID?</p>
[ { "answer_id": 180965, "author": "SeventhSteel", "author_id": 17276, "author_profile": "https://wordpress.stackexchange.com/users/17276", "pm_score": 4, "selected": true, "text": "<p>You're probably getting that error because WordPress doesn't have the $wp_rewrite global loaded yet for some reason. Either something deactivated it, or you're trying to run those functions before WordPress has a chance to load it.</p>\n\n<p>If you're trying to do this in a plugin or in your theme's functions.php file, make sure you're inside a function that is hooked to after_setup_theme or <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"noreferrer\">a hook that runs sometime after</a>. For example:</p>\n\n<pre><code>function get_url_of_page_id_165() {\n return get_permalink( 165 );\n}\nadd_action( 'after_setup_theme', 'get_url_of_page_id_165' );\n</code></pre>\n" }, { "answer_id": 397342, "author": "Maulik patel", "author_id": 171655, "author_profile": "https://wordpress.stackexchange.com/users/171655", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\n$booking_url = get_permalink('15551');\necho $booking_url;\n?&gt;\n</code></pre>\n" } ]
2015/03/12
[ "https://wordpress.stackexchange.com/questions/180964", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68961/" ]
I tried to use get\_page\_link('page-id') and get\_permalink('page-id') but the error below occurred. > > **Fatal error:** Call to a member function get\_page\_permastruct() on null in ... > > > How can I get a page url knowing only its ID?
You're probably getting that error because WordPress doesn't have the $wp\_rewrite global loaded yet for some reason. Either something deactivated it, or you're trying to run those functions before WordPress has a chance to load it. If you're trying to do this in a plugin or in your theme's functions.php file, make sure you're inside a function that is hooked to after\_setup\_theme or [a hook that runs sometime after](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request). For example: ``` function get_url_of_page_id_165() { return get_permalink( 165 ); } add_action( 'after_setup_theme', 'get_url_of_page_id_165' ); ```
180,994
<p>I'm creating a complex site with a product catalog with two custom taxonomies. They are Brands and Types.</p> <p>Brands - Canon - Toshiba - HP</p> <p>Types - Printers - Scanners - Multifunction</p> <p>I need a page that finds all products that are any combination of one brand and one type. The brand is the more important of the two, so it should be filtered as Brand -> Type (although it'd be ideal if this was interchangeable).</p> <p>I can do this by modifying the query based off of a parameter I add to the end of the URL. For example, this URL could be one of the following:</p> <ul> <li><a href="http://www.example.com/brand/canon/?type=printers" rel="nofollow">http://www.example.com/brand/canon/?type=printers</a></li> <li><a href="http://www.example.com/brand/canon/?type=scanners" rel="nofollow">http://www.example.com/brand/canon/?type=scanners</a></li> <li><a href="http://www.example.com/brand/canon/?type=multifunction" rel="nofollow">http://www.example.com/brand/canon/?type=multifunction</a></li> <li><a href="http://www.example.com/brand/toshiba/?type=printers" rel="nofollow">http://www.example.com/brand/toshiba/?type=printers</a></li> <li><a href="http://www.example.com/brand/toshiba/?type=scanners" rel="nofollow">http://www.example.com/brand/toshiba/?type=scanners</a></li> <li><a href="http://www.example.com/brand/toshiba/?type=multifunction" rel="nofollow">http://www.example.com/brand/toshiba/?type=multifunction</a></li> <li><a href="http://www.example.com/brand/hp/?type=printers" rel="nofollow">http://www.example.com/brand/hp/?type=printers</a></li> <li><a href="http://www.example.com/brand/hp/?type=scanners" rel="nofollow">http://www.example.com/brand/hp/?type=scanners</a></li> <li><a href="http://www.example.com/brand/hp/?type=multifunction" rel="nofollow">http://www.example.com/brand/hp/?type=multifunction</a></li> </ul> <p>But I've been told this isn't great for SEO purposes. Ideally, I'd like the URL to be structured as <a href="http://www.example.com/brand/type/" rel="nofollow">http://www.example.com/brand/type/</a>. This would result in URLs like:</p> <ul> <li><a href="http://www.example.com/canon/printers" rel="nofollow">http://www.example.com/canon/printers</a></li> <li><a href="http://www.example.com/canon/scanners" rel="nofollow">http://www.example.com/canon/scanners</a></li> <li><a href="http://www.example.com/canon/multifunction" rel="nofollow">http://www.example.com/canon/multifunction</a></li> <li><a href="http://www.example.com/toshiba/printers" rel="nofollow">http://www.example.com/toshiba/printers</a></li> <li><a href="http://www.example.com/toshiba/scanners" rel="nofollow">http://www.example.com/toshiba/scanners</a></li> <li><a href="http://www.example.com/toshiba/multifunction" rel="nofollow">http://www.example.com/toshiba/multifunction</a></li> <li><a href="http://www.example.com/hp/printers" rel="nofollow">http://www.example.com/hp/printers</a></li> <li><a href="http://www.example.com/hp/scanners" rel="nofollow">http://www.example.com/hp/scanners</a></li> <li><a href="http://www.example.com/hp/multifunction" rel="nofollow">http://www.example.com/hp/multifunction</a></li> </ul> <p>Yes, I know I could set up sub-cateogires for each product type under each brand, but I also need to be able to view all products under each product type irrelevant of brand.</p> <p>By the way, if the URL needs to be a little more complex (i.e. /brand/hp/type/multifunction/) that's better than nothing.</p> <p>Is there some trickery with permalinks I could do to get the links to be structured the way I need them to be?</p> <p><strong>UPDATE 10/23/15:</strong> I just spent an hour trying to diagnose why this stopped working on the site I had built. Turns out I was overriding the default query with a custom one on one of the taxonomy archive templates. To combat this, you can do the following:</p> <pre><code>&lt;?php $tax_query = $wp_query-&gt;query_vars; ?&gt; &lt;?php if ($tax_query["types"] &amp;&amp; $tax_query["brands"]) { // default query stuff here } else { // custom query stuff here } ?&gt; </code></pre>
[ { "answer_id": 181003, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>This rewrite rule should work (assuming \"brand\" and \"type\" are the taxonomy registered names):</p>\n\n<pre><code>function custom_rewrite_rules() {\n add_rewrite_rule('^brand/(.*)/type/(.*)?', 'index.php?brand=$matches[1]&amp;type=$matches[2]', 'top');\n}\nadd_action('init', 'custom_rewrite_rules');\n</code></pre>\n\n<p>Remember to flush the rewirte rules after saving this code in your site.</p>\n\n<p>Then you will need to hook in several places to <em>fix</em> things. For example, you may need to hook <code>wp_title</code> to generate the correct title for the document, for example \"HP Printers\" instead or just \"HP\", as this won't be handle automatically by WordPress. I can't give a exhaustive list of things you will need to <em>fix</em>.</p>\n" }, { "answer_id": 213837, "author": "gmanousaridis", "author_id": 86335, "author_profile": "https://wordpress.stackexchange.com/users/86335", "pm_score": 2, "selected": false, "text": "<p>While digging up to answer <a href=\"https://stackoverflow.com/questions/34351477/combine-multiple-custom-user-taxonomy-in-single-url/34624138\">this one</a>, I found <a href=\"http://thereforei.am/2011/10/28/advanced-taxonomy-queries-with-pretty-urls/\" rel=\"nofollow noreferrer\">here</a> the following rewrite function:</p>\n\n<pre><code>function eg_add_rewrite_rules() {\n global $wp_rewrite;\n $new_rules = array(\n 'user/(profession|city)/(.+?)/(profession|city)/(.+?)/?$' =&gt; 'index.php?post_type=eg_event&amp;' . $wp_rewrite-&gt;preg_index(1) . '=' . $wp_rewrite-&gt;preg_index(2) . '&amp;' . $wp_rewrite-&gt;preg_index(3) . '=' . $wp_rewrite-&gt;preg_index(4),\n 'user/(profession|city)/(.+)/?$' =&gt; 'index.php?post_type=eg_event&amp;' . $wp_rewrite-&gt;preg_index(1) . '=' . $wp_rewrite-&gt;preg_index(2)\n );\n $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules;\n}\nadd_action( 'generate_rewrite_rules', 'eg_add_rewrite_rules' );\n</code></pre>\n\n<p>this function takes a url like: example.com/user/profession/designer,knight/city/athens,gotham/ and converts it in variables:</p>\n\n<pre><code>$proffession = \"designer,knight\";\n$city = \"athens,gotham\";\n</code></pre>\n\n<p>which can be used in the taxonomy.php</p>\n\n<p>More info: <a href=\"https://stackoverflow.com/a/34624138/5594521\">https://stackoverflow.com/a/34624138/5594521</a></p>\n\n<p>Working demo: <a href=\"http://playground.georgemanousarides.com/\" rel=\"nofollow noreferrer\">http://playground.georgemanousarides.com/</a></p>\n\n<p>Hope it helps!</p>\n" } ]
2015/03/12
[ "https://wordpress.stackexchange.com/questions/180994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24566/" ]
I'm creating a complex site with a product catalog with two custom taxonomies. They are Brands and Types. Brands - Canon - Toshiba - HP Types - Printers - Scanners - Multifunction I need a page that finds all products that are any combination of one brand and one type. The brand is the more important of the two, so it should be filtered as Brand -> Type (although it'd be ideal if this was interchangeable). I can do this by modifying the query based off of a parameter I add to the end of the URL. For example, this URL could be one of the following: * <http://www.example.com/brand/canon/?type=printers> * <http://www.example.com/brand/canon/?type=scanners> * <http://www.example.com/brand/canon/?type=multifunction> * <http://www.example.com/brand/toshiba/?type=printers> * <http://www.example.com/brand/toshiba/?type=scanners> * <http://www.example.com/brand/toshiba/?type=multifunction> * <http://www.example.com/brand/hp/?type=printers> * <http://www.example.com/brand/hp/?type=scanners> * <http://www.example.com/brand/hp/?type=multifunction> But I've been told this isn't great for SEO purposes. Ideally, I'd like the URL to be structured as <http://www.example.com/brand/type/>. This would result in URLs like: * <http://www.example.com/canon/printers> * <http://www.example.com/canon/scanners> * <http://www.example.com/canon/multifunction> * <http://www.example.com/toshiba/printers> * <http://www.example.com/toshiba/scanners> * <http://www.example.com/toshiba/multifunction> * <http://www.example.com/hp/printers> * <http://www.example.com/hp/scanners> * <http://www.example.com/hp/multifunction> Yes, I know I could set up sub-cateogires for each product type under each brand, but I also need to be able to view all products under each product type irrelevant of brand. By the way, if the URL needs to be a little more complex (i.e. /brand/hp/type/multifunction/) that's better than nothing. Is there some trickery with permalinks I could do to get the links to be structured the way I need them to be? **UPDATE 10/23/15:** I just spent an hour trying to diagnose why this stopped working on the site I had built. Turns out I was overriding the default query with a custom one on one of the taxonomy archive templates. To combat this, you can do the following: ``` <?php $tax_query = $wp_query->query_vars; ?> <?php if ($tax_query["types"] && $tax_query["brands"]) { // default query stuff here } else { // custom query stuff here } ?> ```
This rewrite rule should work (assuming "brand" and "type" are the taxonomy registered names): ``` function custom_rewrite_rules() { add_rewrite_rule('^brand/(.*)/type/(.*)?', 'index.php?brand=$matches[1]&type=$matches[2]', 'top'); } add_action('init', 'custom_rewrite_rules'); ``` Remember to flush the rewirte rules after saving this code in your site. Then you will need to hook in several places to *fix* things. For example, you may need to hook `wp_title` to generate the correct title for the document, for example "HP Printers" instead or just "HP", as this won't be handle automatically by WordPress. I can't give a exhaustive list of things you will need to *fix*.
181,000
<p>Is there a specific method to get attachment/image info in JS? I have an attachment id and before I use any </p> <pre><code>add_action("wp_ajax_get_image_info", "get_image_info"); </code></pre> <p>I would like to see if there is a native method for doing this trough JS only. </p>
[ { "answer_id": 181018, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Jetpack has a JSON API that allows you to query pretty much everything in a given install. <a href=\"http://jetpack.me/support/json-api/\" rel=\"nofollow\">http://jetpack.me/support/json-api/</a></p>\n" }, { "answer_id": 237574, "author": "Andrei Glingeanu", "author_id": 85925, "author_profile": "https://wordpress.stackexchange.com/users/85925", "pm_score": 5, "selected": true, "text": "<p>Long story short, you can get info about an attachment by using <code>wp.media.attachment()</code> function. This will give you complete data as long as this attachment is already loaded by another script or an <code>wp.media()</code> popup. </p>\n\n<p>If the data is not yet loaded, you can load it using <code>.fetch()</code> method on attachment, which works because it is a <a href=\"http://backbonejs.org/#Collection-fetch\" rel=\"noreferrer\"><code>Backbone.Collection</code></a>. It is a <code>Collection</code> because an attachment may have multiple selected files in it.</p>\n\n<pre><code>// preload your attachment\nwp.media.attachment(ID).fetch().then(function (data) {\n // preloading finished\n // after this you can use your attachment normally\n wp.media.attachment(ID).get('url');\n});\n</code></pre>\n\n<hr>\n\n<p>Easy way of doing preloading:</p>\n\n<pre><code>function preloadAttachment(ID, callback) {\n // if it doesn't have URL we probably have to preload it\n if (wp.media.attachment(ID).get('url')) {\n wp.media.attachment(ID).fetch().then(function () {\n callback(wp.media.attachment(ID);\n });\n\n return;\n }\n\n callback(wp.media.attachment(ID));\n}\n\n// USAGE:\npreloadAttachment(10, function (attachment) {\n console.log(attachment.get('url'));\n console.log(wp.media.attachment(10).get('url')); // this also works\n})\n</code></pre>\n\n<hr>\n\n<p>And that's how you will want to go about preloading more than one <em>attachment</em>, in a single AJAX request.</p>\n\n<pre><code>// An array of attachments you may want to preload\nvar attachment_ids = [10, 11, 12, 13];\nwp.media.query({ post__in: attachment_ids })\n .more()\n .then(function () {\n // You attachments here normally\n // You can safely use any of them here\n wp.media.attachment(10).get('url');\n })\n</code></pre>\n\n<p>Note the fact that the AJAX request performed by <code>wp.media.query()</code> is paginated. If you need a robust solution for loading lots and lots of attachments you should go about parsing each page with <a href=\"https://github.com/WordPress/WordPress/blob/5f4497f0af1f18137e1f109e5b10f4a30ffb49b5/wp-includes/js/media-models.js#L708-L740\" rel=\"noreferrer\"><code>hasMore()</code> and <code>more()</code> methods</a>.</p>\n\n<p>Disclaimer:</p>\n\n<p>I have used this method before finding out about <code>wp.media.query</code> but it has the penalty of making one request per preloaded attachment. But it also has a nice feature -- it doesn't make any request if all of the attachments that need to be preloaded are already in the fetched state.</p>\n\n<pre><code>function preloadMultipleAttachments(attachment_ids) {\n // I'd rather use Promise.all() here but they do not work with\n // jQuery deferreds :/\n if (jQuery.when.all===undefined) {\n jQuery.when.all = function(deferreds) {\n var deferred = new jQuery.Deferred();\n $.when.apply(jQuery, deferreds).then(\n function() {\n deferred.resolve(Array.prototype.slice.call(arguments));\n },\n function() {\n deferred.fail(Array.prototype.slice.call(arguments));\n });\n\n return deferred;\n }\n }\n\n return jQuery.when.all(\n attachment_ids.filter(function (attachment_id) {\n return ! wp.media.attachment(attachment_id).get('url');\n }).map(function (id) {\n return wp.media.attachment(id).fetch();\n })\n );\n},\n</code></pre>\n" } ]
2015/03/12
[ "https://wordpress.stackexchange.com/questions/181000", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67176/" ]
Is there a specific method to get attachment/image info in JS? I have an attachment id and before I use any ``` add_action("wp_ajax_get_image_info", "get_image_info"); ``` I would like to see if there is a native method for doing this trough JS only.
Long story short, you can get info about an attachment by using `wp.media.attachment()` function. This will give you complete data as long as this attachment is already loaded by another script or an `wp.media()` popup. If the data is not yet loaded, you can load it using `.fetch()` method on attachment, which works because it is a [`Backbone.Collection`](http://backbonejs.org/#Collection-fetch). It is a `Collection` because an attachment may have multiple selected files in it. ``` // preload your attachment wp.media.attachment(ID).fetch().then(function (data) { // preloading finished // after this you can use your attachment normally wp.media.attachment(ID).get('url'); }); ``` --- Easy way of doing preloading: ``` function preloadAttachment(ID, callback) { // if it doesn't have URL we probably have to preload it if (wp.media.attachment(ID).get('url')) { wp.media.attachment(ID).fetch().then(function () { callback(wp.media.attachment(ID); }); return; } callback(wp.media.attachment(ID)); } // USAGE: preloadAttachment(10, function (attachment) { console.log(attachment.get('url')); console.log(wp.media.attachment(10).get('url')); // this also works }) ``` --- And that's how you will want to go about preloading more than one *attachment*, in a single AJAX request. ``` // An array of attachments you may want to preload var attachment_ids = [10, 11, 12, 13]; wp.media.query({ post__in: attachment_ids }) .more() .then(function () { // You attachments here normally // You can safely use any of them here wp.media.attachment(10).get('url'); }) ``` Note the fact that the AJAX request performed by `wp.media.query()` is paginated. If you need a robust solution for loading lots and lots of attachments you should go about parsing each page with [`hasMore()` and `more()` methods](https://github.com/WordPress/WordPress/blob/5f4497f0af1f18137e1f109e5b10f4a30ffb49b5/wp-includes/js/media-models.js#L708-L740). Disclaimer: I have used this method before finding out about `wp.media.query` but it has the penalty of making one request per preloaded attachment. But it also has a nice feature -- it doesn't make any request if all of the attachments that need to be preloaded are already in the fetched state. ``` function preloadMultipleAttachments(attachment_ids) { // I'd rather use Promise.all() here but they do not work with // jQuery deferreds :/ if (jQuery.when.all===undefined) { jQuery.when.all = function(deferreds) { var deferred = new jQuery.Deferred(); $.when.apply(jQuery, deferreds).then( function() { deferred.resolve(Array.prototype.slice.call(arguments)); }, function() { deferred.fail(Array.prototype.slice.call(arguments)); }); return deferred; } } return jQuery.when.all( attachment_ids.filter(function (attachment_id) { return ! wp.media.attachment(attachment_id).get('url'); }).map(function (id) { return wp.media.attachment(id).fetch(); }) ); }, ```
181,012
<p>I've registered an <code>employers</code> post type with several associated taxonomies and want to all associated pages (single, term archives, post type archive page) only viewable by logged-in users.</p> <p>I've played around with the <code>capabilities</code> argument for <code>register_post_type()</code> and looked at the <code>map_meta_cap</code> filter, but just can't quite put the pieces together. It seems that maybe I need to use a custom capability but that feels like overkill for this one feature. I've seen some references to using the <code>template_redirect</code> feature too but not sure if that's the right way to go.</p> <p>Despite a lot of searching, I'm struggling to answer what feels like a simple question. How can I restrict access of a custom post type or custom taxonomy to logged-in users of any capability?</p> <p>I've seen "<a href="https://wordpress.stackexchange.com/questions/96910/restrict-custom-post-type-view-by-user-role">Restrict custom post type view by user role</a>" but that's only filters <code>the_content</code>. I've also looked a lot at "<a href="https://wordpress.stackexchange.com/questions/54959/restrict-custom-post-type-to-only-site-administrator-role">Restrict custom post type to only site administrator role</a>" but it seems more about logged-in users. Finally "<a href="https://wordpress.stackexchange.com/questions/118970/set-posts-of-a-custom-post-type-to-be-private-by-default">Set posts of a custom post type to be private by default?</a>" only sets the post status meaning that an editor could accidentally make the post public which is a dealbreaker.</p>
[ { "answer_id": 181017, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I may be misreading what you want, but you can do this with current_user_can() in your template.</p>\n\n<pre><code>if( ! current_user_can( 'read' ) {\n echo \"You must log in to see this content.\";\n}\nelse {\n //The Loop goes here\n}\n</code></pre>\n\n<p>The problem with this is that it doesn't cache; or, at least, it doesn't cache well, especially if you are using a file-only cache.</p>\n" }, { "answer_id": 181089, "author": "Travis Seitler", "author_id": 49522, "author_profile": "https://wordpress.stackexchange.com/users/49522", "pm_score": 2, "selected": false, "text": "<p>I've faced similar situations (say a client wants to see how a custom post type and/or taxonomy behaves before they're ready for the general public to see it). In those cases I'll use something like the following code snippet, added either to the plugin file (assuming I've built the CPT/taxonomy as a plugin) or directly in the active theme's functions.php:</p>\n\n<pre><code>/**\n * IN-DEVELOPMENT REDIRECTS\n * While specified areas are under development, redirect users to home page if not logged in\n */\nadd_filter( 'wp', 'f040925b_redirect', 0 );\nfunction f040925b_redirect( $content ) {\n global $post;\n if(\n (\n $post-&gt;post_type == '[custom_post_type_name]'\n ||\n is_post_type_archive( '[custom_post_type_name]' )\n ||\n is_tax( '[custom_taxonomy_name]' )\n )\n &amp;&amp;\n !is_user_logged_in()\n ) {\n wp_redirect( get_home_url() );\n exit;\n }\n return $content;\n}\n</code></pre>\n\n<p>Essentially, this runs three early checks:</p>\n\n<ol>\n<li>Does the $post object's post type match what you're trying to hide?</li>\n<li>Is this URL a post type archive for the post type you're trying to hide?</li>\n<li>Is this URL a taxonomy/term page for the taxonomy you're trying to hide?</li>\n</ol>\n\n<p>If any of these is a match <em>and</em> the user is not logged in, then the user is redirected to the site's homepage.</p>\n" } ]
2015/03/12
[ "https://wordpress.stackexchange.com/questions/181012", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9844/" ]
I've registered an `employers` post type with several associated taxonomies and want to all associated pages (single, term archives, post type archive page) only viewable by logged-in users. I've played around with the `capabilities` argument for `register_post_type()` and looked at the `map_meta_cap` filter, but just can't quite put the pieces together. It seems that maybe I need to use a custom capability but that feels like overkill for this one feature. I've seen some references to using the `template_redirect` feature too but not sure if that's the right way to go. Despite a lot of searching, I'm struggling to answer what feels like a simple question. How can I restrict access of a custom post type or custom taxonomy to logged-in users of any capability? I've seen "[Restrict custom post type view by user role](https://wordpress.stackexchange.com/questions/96910/restrict-custom-post-type-view-by-user-role)" but that's only filters `the_content`. I've also looked a lot at "[Restrict custom post type to only site administrator role](https://wordpress.stackexchange.com/questions/54959/restrict-custom-post-type-to-only-site-administrator-role)" but it seems more about logged-in users. Finally "[Set posts of a custom post type to be private by default?](https://wordpress.stackexchange.com/questions/118970/set-posts-of-a-custom-post-type-to-be-private-by-default)" only sets the post status meaning that an editor could accidentally make the post public which is a dealbreaker.
I've faced similar situations (say a client wants to see how a custom post type and/or taxonomy behaves before they're ready for the general public to see it). In those cases I'll use something like the following code snippet, added either to the plugin file (assuming I've built the CPT/taxonomy as a plugin) or directly in the active theme's functions.php: ``` /** * IN-DEVELOPMENT REDIRECTS * While specified areas are under development, redirect users to home page if not logged in */ add_filter( 'wp', 'f040925b_redirect', 0 ); function f040925b_redirect( $content ) { global $post; if( ( $post->post_type == '[custom_post_type_name]' || is_post_type_archive( '[custom_post_type_name]' ) || is_tax( '[custom_taxonomy_name]' ) ) && !is_user_logged_in() ) { wp_redirect( get_home_url() ); exit; } return $content; } ``` Essentially, this runs three early checks: 1. Does the $post object's post type match what you're trying to hide? 2. Is this URL a post type archive for the post type you're trying to hide? 3. Is this URL a taxonomy/term page for the taxonomy you're trying to hide? If any of these is a match *and* the user is not logged in, then the user is redirected to the site's homepage.
181,070
<p>How can I add an input field to the admin section Users -> Add New?</p> <p>I want to add a field for a phone number, but don't want a plugin to do that.</p>
[ { "answer_id": 181071, "author": "Bird87 ZA", "author_id": 59212, "author_profile": "https://wordpress.stackexchange.com/users/59212", "pm_score": 3, "selected": true, "text": "<p>Okay found the answer by poking around the code</p>\n\n<p>A field can be added by doing the following:</p>\n\n<pre><code>add_action('user_new_form','myplugin_add_field');\n\nfunction myplugin_add_field() {\n // code to add field\n}\n</code></pre>\n" }, { "answer_id": 181098, "author": "seot", "author_id": 34534, "author_profile": "https://wordpress.stackexchange.com/users/34534", "pm_score": 0, "selected": false, "text": "<p>in <a href=\"http://plugins.svn.wordpress.org/hrm-work-tracking/trunk/hrm-users.php\" rel=\"nofollow\">http://plugins.svn.wordpress.org/hrm-work-tracking/trunk/hrm-users.php</a> I found such thing with</p>\n\n<pre><code>add_action( 'show_user_profile', '' );\nadd_action( 'edit_user_profile', '' );\nadd_action( 'personal_options_update', '' );\nadd_action( 'edit_user_profile_update', '' );\n</code></pre>\n\n<p>I dont know another way for this</p>\n" }, { "answer_id": 181115, "author": "Brad Elsmore", "author_id": 69036, "author_profile": "https://wordpress.stackexchange.com/users/69036", "pm_score": 2, "selected": false, "text": "<p>Here's the way I have always done it. All of this code goes in functions.php. Of course this adds a whole new section to the user profile.</p>\n\n<pre><code>add_action( 'show_user_profile', 'be_show_extra_profile_fields' );\nadd_action( 'edit_user_profile', 'be_show_extra_profile_fields' );\n\nfunction be_show_extra_profile_fields( $user ) { ?&gt;\n\n &lt;h3&gt;Extra Contact Information&lt;/h3&gt;\n\n &lt;table class=\"form-table\"&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=\"contact\"&gt;Contact Number&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"contact\" id=\"contact\" value=\"&lt;?php echo esc_attr( get_the_author_meta( 'contact', $user-&gt;ID ) ); ?&gt;\" class=\"regular-text\" /&gt;&lt;br /&gt;\n &lt;span class=\"description\"&gt;Please enter your phone number.&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;?php } \nadd_action( 'personal_options_update', 'be_save_extra_profile_fields' );\nadd_action( 'edit_user_profile_update', 'be_save_extra_profile_fields' );\n\nfunction be_save_extra_profile_fields( $user_id ) {\n\n if ( ! current_user_can( 'edit_user', $user_id ) ) {\n return false;\n }\n\n update_usermeta( $user_id, 'contact', esc_attr( $_POST['contact'] ) );\n}\n</code></pre>\n\n<p>Alternatively If you want to add some contact methods to the already existing section in the user profile you can use the following and it's a little cleaner. Below is the function i usually use to get rid of outdated social platforms and add some new ones for users.</p>\n\n<pre><code>add_filter( 'user_contactmethods', 'be_hide_profile_fields', 10, 1 );\nfunction be_hide_profile_fields( $contactmethods ) {\n unset($contactmethods['aim']);\n unset($contactmethods['jabber']);\n unset($contactmethods['yim']);\n\n $contactmethods['twitter'] = 'Twitter';\n $contactmethods['facebook'] = 'Facebook';\n $contactmethods['linkedin'] = 'LinkedIn';\n return $contactmethods;\n}\n</code></pre>\n\n<p>If you wanted to add a phone number to that you could just add something like</p>\n\n<pre><code>$contactmethods['phonenumber'] = 'Phone Number;\n</code></pre>\n\n<p>to the function above and it will create the field for you.</p>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181070", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59212/" ]
How can I add an input field to the admin section Users -> Add New? I want to add a field for a phone number, but don't want a plugin to do that.
Okay found the answer by poking around the code A field can be added by doing the following: ``` add_action('user_new_form','myplugin_add_field'); function myplugin_add_field() { // code to add field } ```
181,073
<p>I'm trying to add the following hook into my functions.php file. The CSS style shows up when I view the source code but it also show the php code for the random background image generator. How can I get the php in that line to work within the hook?</p> <p>Thanks</p> <pre><code>add_action('wp_head','hook_css'); function hook_css() { $output=" &lt;style&gt; body { background-repeat: no-repeat; background-attachment: fixed; background-size: 100% 100%; background: url('../images/backgrounds/bg&lt;?php echo rand(1,4)?&gt;.jpg') no-repeat top center; } &lt;/style&gt;"; echo $output; } </code></pre>
[ { "answer_id": 181071, "author": "Bird87 ZA", "author_id": 59212, "author_profile": "https://wordpress.stackexchange.com/users/59212", "pm_score": 3, "selected": true, "text": "<p>Okay found the answer by poking around the code</p>\n\n<p>A field can be added by doing the following:</p>\n\n<pre><code>add_action('user_new_form','myplugin_add_field');\n\nfunction myplugin_add_field() {\n // code to add field\n}\n</code></pre>\n" }, { "answer_id": 181098, "author": "seot", "author_id": 34534, "author_profile": "https://wordpress.stackexchange.com/users/34534", "pm_score": 0, "selected": false, "text": "<p>in <a href=\"http://plugins.svn.wordpress.org/hrm-work-tracking/trunk/hrm-users.php\" rel=\"nofollow\">http://plugins.svn.wordpress.org/hrm-work-tracking/trunk/hrm-users.php</a> I found such thing with</p>\n\n<pre><code>add_action( 'show_user_profile', '' );\nadd_action( 'edit_user_profile', '' );\nadd_action( 'personal_options_update', '' );\nadd_action( 'edit_user_profile_update', '' );\n</code></pre>\n\n<p>I dont know another way for this</p>\n" }, { "answer_id": 181115, "author": "Brad Elsmore", "author_id": 69036, "author_profile": "https://wordpress.stackexchange.com/users/69036", "pm_score": 2, "selected": false, "text": "<p>Here's the way I have always done it. All of this code goes in functions.php. Of course this adds a whole new section to the user profile.</p>\n\n<pre><code>add_action( 'show_user_profile', 'be_show_extra_profile_fields' );\nadd_action( 'edit_user_profile', 'be_show_extra_profile_fields' );\n\nfunction be_show_extra_profile_fields( $user ) { ?&gt;\n\n &lt;h3&gt;Extra Contact Information&lt;/h3&gt;\n\n &lt;table class=\"form-table\"&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=\"contact\"&gt;Contact Number&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"contact\" id=\"contact\" value=\"&lt;?php echo esc_attr( get_the_author_meta( 'contact', $user-&gt;ID ) ); ?&gt;\" class=\"regular-text\" /&gt;&lt;br /&gt;\n &lt;span class=\"description\"&gt;Please enter your phone number.&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;?php } \nadd_action( 'personal_options_update', 'be_save_extra_profile_fields' );\nadd_action( 'edit_user_profile_update', 'be_save_extra_profile_fields' );\n\nfunction be_save_extra_profile_fields( $user_id ) {\n\n if ( ! current_user_can( 'edit_user', $user_id ) ) {\n return false;\n }\n\n update_usermeta( $user_id, 'contact', esc_attr( $_POST['contact'] ) );\n}\n</code></pre>\n\n<p>Alternatively If you want to add some contact methods to the already existing section in the user profile you can use the following and it's a little cleaner. Below is the function i usually use to get rid of outdated social platforms and add some new ones for users.</p>\n\n<pre><code>add_filter( 'user_contactmethods', 'be_hide_profile_fields', 10, 1 );\nfunction be_hide_profile_fields( $contactmethods ) {\n unset($contactmethods['aim']);\n unset($contactmethods['jabber']);\n unset($contactmethods['yim']);\n\n $contactmethods['twitter'] = 'Twitter';\n $contactmethods['facebook'] = 'Facebook';\n $contactmethods['linkedin'] = 'LinkedIn';\n return $contactmethods;\n}\n</code></pre>\n\n<p>If you wanted to add a phone number to that you could just add something like</p>\n\n<pre><code>$contactmethods['phonenumber'] = 'Phone Number;\n</code></pre>\n\n<p>to the function above and it will create the field for you.</p>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181073", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6787/" ]
I'm trying to add the following hook into my functions.php file. The CSS style shows up when I view the source code but it also show the php code for the random background image generator. How can I get the php in that line to work within the hook? Thanks ``` add_action('wp_head','hook_css'); function hook_css() { $output=" <style> body { background-repeat: no-repeat; background-attachment: fixed; background-size: 100% 100%; background: url('../images/backgrounds/bg<?php echo rand(1,4)?>.jpg') no-repeat top center; } </style>"; echo $output; } ```
Okay found the answer by poking around the code A field can be added by doing the following: ``` add_action('user_new_form','myplugin_add_field'); function myplugin_add_field() { // code to add field } ```
181,086
<p>for example, i had all ftp content (wordpress instalation php files) backup, and hacker got that backup file and looked into all php files(including config.php and etc) ... can he somehow access my wordpress site?<br> remote database is disabled..</p>
[ { "answer_id": 181071, "author": "Bird87 ZA", "author_id": 59212, "author_profile": "https://wordpress.stackexchange.com/users/59212", "pm_score": 3, "selected": true, "text": "<p>Okay found the answer by poking around the code</p>\n\n<p>A field can be added by doing the following:</p>\n\n<pre><code>add_action('user_new_form','myplugin_add_field');\n\nfunction myplugin_add_field() {\n // code to add field\n}\n</code></pre>\n" }, { "answer_id": 181098, "author": "seot", "author_id": 34534, "author_profile": "https://wordpress.stackexchange.com/users/34534", "pm_score": 0, "selected": false, "text": "<p>in <a href=\"http://plugins.svn.wordpress.org/hrm-work-tracking/trunk/hrm-users.php\" rel=\"nofollow\">http://plugins.svn.wordpress.org/hrm-work-tracking/trunk/hrm-users.php</a> I found such thing with</p>\n\n<pre><code>add_action( 'show_user_profile', '' );\nadd_action( 'edit_user_profile', '' );\nadd_action( 'personal_options_update', '' );\nadd_action( 'edit_user_profile_update', '' );\n</code></pre>\n\n<p>I dont know another way for this</p>\n" }, { "answer_id": 181115, "author": "Brad Elsmore", "author_id": 69036, "author_profile": "https://wordpress.stackexchange.com/users/69036", "pm_score": 2, "selected": false, "text": "<p>Here's the way I have always done it. All of this code goes in functions.php. Of course this adds a whole new section to the user profile.</p>\n\n<pre><code>add_action( 'show_user_profile', 'be_show_extra_profile_fields' );\nadd_action( 'edit_user_profile', 'be_show_extra_profile_fields' );\n\nfunction be_show_extra_profile_fields( $user ) { ?&gt;\n\n &lt;h3&gt;Extra Contact Information&lt;/h3&gt;\n\n &lt;table class=\"form-table\"&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=\"contact\"&gt;Contact Number&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"text\" name=\"contact\" id=\"contact\" value=\"&lt;?php echo esc_attr( get_the_author_meta( 'contact', $user-&gt;ID ) ); ?&gt;\" class=\"regular-text\" /&gt;&lt;br /&gt;\n &lt;span class=\"description\"&gt;Please enter your phone number.&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;?php } \nadd_action( 'personal_options_update', 'be_save_extra_profile_fields' );\nadd_action( 'edit_user_profile_update', 'be_save_extra_profile_fields' );\n\nfunction be_save_extra_profile_fields( $user_id ) {\n\n if ( ! current_user_can( 'edit_user', $user_id ) ) {\n return false;\n }\n\n update_usermeta( $user_id, 'contact', esc_attr( $_POST['contact'] ) );\n}\n</code></pre>\n\n<p>Alternatively If you want to add some contact methods to the already existing section in the user profile you can use the following and it's a little cleaner. Below is the function i usually use to get rid of outdated social platforms and add some new ones for users.</p>\n\n<pre><code>add_filter( 'user_contactmethods', 'be_hide_profile_fields', 10, 1 );\nfunction be_hide_profile_fields( $contactmethods ) {\n unset($contactmethods['aim']);\n unset($contactmethods['jabber']);\n unset($contactmethods['yim']);\n\n $contactmethods['twitter'] = 'Twitter';\n $contactmethods['facebook'] = 'Facebook';\n $contactmethods['linkedin'] = 'LinkedIn';\n return $contactmethods;\n}\n</code></pre>\n\n<p>If you wanted to add a phone number to that you could just add something like</p>\n\n<pre><code>$contactmethods['phonenumber'] = 'Phone Number;\n</code></pre>\n\n<p>to the function above and it will create the field for you.</p>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
for example, i had all ftp content (wordpress instalation php files) backup, and hacker got that backup file and looked into all php files(including config.php and etc) ... can he somehow access my wordpress site? remote database is disabled..
Okay found the answer by poking around the code A field can be added by doing the following: ``` add_action('user_new_form','myplugin_add_field'); function myplugin_add_field() { // code to add field } ```
181,108
<p>I'm having trouble implementing a concurrent login check.</p> <p>The site needs to prevent more than 5 concurrent sessions for any particular user at one time. </p> <p><strong>Example:</strong> User Matt can have 5 active sessions. </p> <blockquote> <p>If user Matt tries to login with a 6th session, it will remove the session which logged in first &amp; had no activity older than 4 hours. If all 5 sessions have had activity in the past 4 hours, login fails and the user is presented an error/message to contact site admin.</p> </blockquote> <p>I know Wordpress has WP_Session_Tokens but it seems they only store 'expiration' and 'login' with no 'last_activity'. Is there any way to check for last activity either through Wordpress or PHP Sessions?</p> <p>If not then a secondary question of mine is how best to compare 'last' login to current time and check if it's more than 4 hours.</p> <p>Here is my current code:</p> <pre><code>// On login, check if there are already 5 sessions active for the user function check_sessions($login) { global $user_ID; $user = get_user_by( 'slug', $login ); //If there are less than 5 sessions, let user login normally if( count( wp_get_all_sessions() ) &lt; 5 ) { return true; } $sessions = WP_Session_Tokens::get_instance( $user-&gt;id ); $all_sessions = $sessions-&gt;get_all(); $first_login = $all_sessions[0]['login']; if( $first_login-&gt;diff(time()) &gt; 4hrs ) { // log out first_login user &amp; login new user WP_Session_Tokens::destroy( $all_sessions[0] ); return true; } else { // display message to user } } add_action('wp_login','check_sessions'); </code></pre>
[ { "answer_id": 205107, "author": "Sisir", "author_id": 3094, "author_profile": "https://wordpress.stackexchange.com/users/3094", "pm_score": 4, "selected": false, "text": "<p>This question made me really interested. Took about 5 hours of my Saturday to create the full solution :) </p>\n\n<h2>Plugin Limit Login Sessions</h2>\n\n<p>It doesn't provide a settings page yet, so all options are currently hard coded. The plugin implements the following (according to OP):</p>\n\n<ol>\n<li>A user can have a maximum of 5 login sessions across various browsers and devices.</li>\n<li>If more then 5 sessions are attempted it will show an error, unless the oldest activity session is more then 4 hours old.</li>\n<li>If the oldest activity session is more then 4 hours old, that session will be closed and current attempt of the login is allowed.</li>\n</ol>\n\n<p>I tried to add explanations in the code with comments. Most of the plugin code should be self explanatory. If some part of it is not clear, feel free to comment.</p>\n\n<p><a href=\"https://github.com/prionkor/limit-login-sessions\">The GitHub repository can be found here</a>. Feel free to fork and improve it :) If anyone thinks it would be a useful addition to the WordPress plugin repository, let me know and I will upload to WordPress.org if required.</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Limit Login Sessions\nVersion: 1.0.0\nAuthor: Sisir Kanti Adhikari\nAuthor URI: https://sisir.me/\nDescription: Limits users login sessions.\nLicense: GPLv2 or later\nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html\n\nLimit Login Sessions is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 2 of the License, or\nany later version.\n\nLimit Login Sessions is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License (http://www.gnu.org/licenses/gpl-2.0.html)\n for more details.\n\n*/\n\nadd_filter('authenticate', 'lls_authenticate', 1000, 2);\n\nfunction lls_authenticate($user, $username){\n\n if(!username_exists($username) || !$user = get_user_by('login', $username))\n return null; // will trigger WP default no username/password matched error\n\n // setup vars\n $max_sessions = 5;\n $max_oldest_allowed_session_hours = 4;\n $error_code = 'max_session_reached';\n $error_message = \"Maximum $max_sessions login sessions are allowed. Please contact site administrator.\";\n\n // 1. Get all active session for this user\n $manager = WP_Session_Tokens::get_instance( $user-&gt;ID );\n $sessions = $manager-&gt;get_all();\n\n // 2. Count all active session\n $session_count = count($sessions);\n\n // 3. Return okay if active session less then $max_sessions\n if($session_count &lt; $max_sessions)\n return $user;\n\n $oldest_activity_session = lls_get_oldest_activity_session($sessions);\n\n // 4. If active sessions is equal to 5 then check if a session has no activity last 4 hours\n // 5. if oldest session have activity return error\n if(\n ( $session_count &gt;= $max_sessions &amp;&amp; !$oldest_activity_session ) // if no oldest is found do not allow\n || ( $session_count &gt;= $max_sessions &amp;&amp; $oldest_activity_session['last_activity'] + $max_oldest_allowed_session_hours * HOUR_IN_SECONDS &gt; time())\n ){\n return new WP_Error($error_code, $error_message);\n }\n\n // 5. Oldest activity session doesn't have activity is given recent hours\n // destroy oldest active session and authenticate the user\n\n $verifier = lls_get_verifier_by_session($oldest_activity_session, $user-&gt;ID);\n\n lls_destroy_session($verifier, $user-&gt;ID);\n\n return $user;\n\n}\n\nfunction lls_destroy_session($verifier, $user_id){\n\n $sessions = get_user_meta( $user_id, 'session_tokens', true );\n\n if(!isset($sessions[$verifier]))\n return true;\n\n unset($sessions[$verifier]);\n\n if(!empty($sessions)){\n update_user_meta( $user_id, 'session_tokens', $sessions );\n return true;\n }\n\n delete_user_meta( $user_id, 'session_tokens');\n return true;\n\n}\n\nfunction lls_get_verifier_by_session($session, $user_id = null){\n\n if(!$user_id)\n $user_id = get_current_user_id();\n\n $session_string = implode(',', $session);\n $sessions = get_user_meta( $user_id, 'session_tokens', true );\n\n if(empty($sessions))\n return false;\n\n foreach($sessions as $verifier =&gt; $sess){\n $sess_string = implode(',', $sess);\n\n if($session_string == $sess_string)\n return $verifier;\n\n }\n\n return false;\n}\n\n\nfunction lls_get_oldest_activity_session($sessions){\n $sess = false;\n\n foreach($sessions as $session){\n\n if(!isset($session['last_activity']))\n continue;\n\n if(!$sess){\n $sess = $session;\n continue;\n }\n\n if($sess['last_activity'] &gt; $session['last_activity'])\n $sess = $session;\n\n }\n\n return $sess;\n}\n\n// add a new key to session token array\n\nadd_filter('attach_session_information', 'lls_attach_session_information');\n\nfunction lls_attach_session_information($session){\n $session['last_activity'] = time();\n return $session;\n}\n\nadd_action('template_redirect', 'lls_update_session_last_activity');\n\nfunction lls_update_session_last_activity(){\n\n if(!is_user_logged_in())\n return;\n\n // get the login cookie from browser\n $logged_in_cookie = $_COOKIE[LOGGED_IN_COOKIE];\n\n // check for valid auth cookie\n if( !$cookie_element = wp_parse_auth_cookie($logged_in_cookie) )\n return;\n\n // get the current session\n $manager = WP_Session_Tokens::get_instance( get_current_user_id() );\n\n $current_session = $manager-&gt;get($cookie_element['token']);\n\n if(\n $current_session['expiration'] &lt;= time() // only update if session is not expired\n || ( $current_session['last_activity'] + 5 * MINUTE_IN_SECONDS ) &gt; time() // only update in every 5 min to reduce db load\n ){\n return;\n }\n\n $current_session['last_activity'] = time();\n $manager-&gt;update($cookie_element['token'], $current_session);\n\n}\n</code></pre>\n\n<p>For some functionality, I had to directly interact with the database <code>user_meta</code> value. The class had some methods protected, so couldn't be accessed directly. </p>\n\n<p>Plugin is tested locally with WP <code>v4.3.1</code>.</p>\n" }, { "answer_id": 205119, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>It is impossible to have an answer for the question as it is being asked because http protocol do not have any long term sessions. A session on http is one request and response.</p>\n\n<p>Sessions as we know on the internet are just hacks designed to remove the need to provide login and pass info for every page load.</p>\n\n<p>wordpress 4.1 done a small step in better associating a \"session\" with an end device, but it is just a better hack than before and it is not 100% reliable as you can still copy the cookies and/or use proxy to foul it into believing that two separate end devices belong to the same session. OTOH it will think that two browser on the same machine are on different devices.</p>\n\n<p>You are just trying to make DRM work, and for the last 20 years there was one thing proven about DRM, 1. It does not prevent people from getting \"illegal\" access to content, it just takes a little longer. 2. It annoys the paying clients.</p>\n\n<p>Your specific scheme depends on knowing which device is going to be used next, and your assumption that it is the one which was most recently active has no merit. OTOH 5 active session will probably be enough for my whole block, so you don't even \"block content stealing\"</p>\n\n<p>It is not that the question has no merit at all. I can see something like that used to enhance security, but DRM depends very much on the small details and once you use a vogue but critical term like \"active sessions\" without defining the details of it first it means for me that you don't really know what you actually expect from the system, as finding out the \"active sessions\" is the most critical part of implementing your scheme.</p>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181108", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69034/" ]
I'm having trouble implementing a concurrent login check. The site needs to prevent more than 5 concurrent sessions for any particular user at one time. **Example:** User Matt can have 5 active sessions. > > If user Matt tries to login with a 6th session, it will remove the session which logged in first & had no activity older than 4 hours. > If all 5 sessions have had activity in the past 4 hours, login fails and the user is presented an error/message to contact site admin. > > > I know Wordpress has WP\_Session\_Tokens but it seems they only store 'expiration' and 'login' with no 'last\_activity'. Is there any way to check for last activity either through Wordpress or PHP Sessions? If not then a secondary question of mine is how best to compare 'last' login to current time and check if it's more than 4 hours. Here is my current code: ``` // On login, check if there are already 5 sessions active for the user function check_sessions($login) { global $user_ID; $user = get_user_by( 'slug', $login ); //If there are less than 5 sessions, let user login normally if( count( wp_get_all_sessions() ) < 5 ) { return true; } $sessions = WP_Session_Tokens::get_instance( $user->id ); $all_sessions = $sessions->get_all(); $first_login = $all_sessions[0]['login']; if( $first_login->diff(time()) > 4hrs ) { // log out first_login user & login new user WP_Session_Tokens::destroy( $all_sessions[0] ); return true; } else { // display message to user } } add_action('wp_login','check_sessions'); ```
This question made me really interested. Took about 5 hours of my Saturday to create the full solution :) Plugin Limit Login Sessions --------------------------- It doesn't provide a settings page yet, so all options are currently hard coded. The plugin implements the following (according to OP): 1. A user can have a maximum of 5 login sessions across various browsers and devices. 2. If more then 5 sessions are attempted it will show an error, unless the oldest activity session is more then 4 hours old. 3. If the oldest activity session is more then 4 hours old, that session will be closed and current attempt of the login is allowed. I tried to add explanations in the code with comments. Most of the plugin code should be self explanatory. If some part of it is not clear, feel free to comment. [The GitHub repository can be found here](https://github.com/prionkor/limit-login-sessions). Feel free to fork and improve it :) If anyone thinks it would be a useful addition to the WordPress plugin repository, let me know and I will upload to WordPress.org if required. ``` <?php /* Plugin Name: Limit Login Sessions Version: 1.0.0 Author: Sisir Kanti Adhikari Author URI: https://sisir.me/ Description: Limits users login sessions. License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Limit Login Sessions is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or any later version. Limit Login Sessions is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License (http://www.gnu.org/licenses/gpl-2.0.html) for more details. */ add_filter('authenticate', 'lls_authenticate', 1000, 2); function lls_authenticate($user, $username){ if(!username_exists($username) || !$user = get_user_by('login', $username)) return null; // will trigger WP default no username/password matched error // setup vars $max_sessions = 5; $max_oldest_allowed_session_hours = 4; $error_code = 'max_session_reached'; $error_message = "Maximum $max_sessions login sessions are allowed. Please contact site administrator."; // 1. Get all active session for this user $manager = WP_Session_Tokens::get_instance( $user->ID ); $sessions = $manager->get_all(); // 2. Count all active session $session_count = count($sessions); // 3. Return okay if active session less then $max_sessions if($session_count < $max_sessions) return $user; $oldest_activity_session = lls_get_oldest_activity_session($sessions); // 4. If active sessions is equal to 5 then check if a session has no activity last 4 hours // 5. if oldest session have activity return error if( ( $session_count >= $max_sessions && !$oldest_activity_session ) // if no oldest is found do not allow || ( $session_count >= $max_sessions && $oldest_activity_session['last_activity'] + $max_oldest_allowed_session_hours * HOUR_IN_SECONDS > time()) ){ return new WP_Error($error_code, $error_message); } // 5. Oldest activity session doesn't have activity is given recent hours // destroy oldest active session and authenticate the user $verifier = lls_get_verifier_by_session($oldest_activity_session, $user->ID); lls_destroy_session($verifier, $user->ID); return $user; } function lls_destroy_session($verifier, $user_id){ $sessions = get_user_meta( $user_id, 'session_tokens', true ); if(!isset($sessions[$verifier])) return true; unset($sessions[$verifier]); if(!empty($sessions)){ update_user_meta( $user_id, 'session_tokens', $sessions ); return true; } delete_user_meta( $user_id, 'session_tokens'); return true; } function lls_get_verifier_by_session($session, $user_id = null){ if(!$user_id) $user_id = get_current_user_id(); $session_string = implode(',', $session); $sessions = get_user_meta( $user_id, 'session_tokens', true ); if(empty($sessions)) return false; foreach($sessions as $verifier => $sess){ $sess_string = implode(',', $sess); if($session_string == $sess_string) return $verifier; } return false; } function lls_get_oldest_activity_session($sessions){ $sess = false; foreach($sessions as $session){ if(!isset($session['last_activity'])) continue; if(!$sess){ $sess = $session; continue; } if($sess['last_activity'] > $session['last_activity']) $sess = $session; } return $sess; } // add a new key to session token array add_filter('attach_session_information', 'lls_attach_session_information'); function lls_attach_session_information($session){ $session['last_activity'] = time(); return $session; } add_action('template_redirect', 'lls_update_session_last_activity'); function lls_update_session_last_activity(){ if(!is_user_logged_in()) return; // get the login cookie from browser $logged_in_cookie = $_COOKIE[LOGGED_IN_COOKIE]; // check for valid auth cookie if( !$cookie_element = wp_parse_auth_cookie($logged_in_cookie) ) return; // get the current session $manager = WP_Session_Tokens::get_instance( get_current_user_id() ); $current_session = $manager->get($cookie_element['token']); if( $current_session['expiration'] <= time() // only update if session is not expired || ( $current_session['last_activity'] + 5 * MINUTE_IN_SECONDS ) > time() // only update in every 5 min to reduce db load ){ return; } $current_session['last_activity'] = time(); $manager->update($cookie_element['token'], $current_session); } ``` For some functionality, I had to directly interact with the database `user_meta` value. The class had some methods protected, so couldn't be accessed directly. Plugin is tested locally with WP `v4.3.1`.
181,111
<p>Sometimes there's no way around creating a custom query, but when I do and then loop through it, I often want to use <code>get_template_part()</code> within the custom query loop to pull in a template I already know will fit my needs. Sometimes that template is 99.9% perfect and only needs some conditionals added for it to behave as needed depending on the query.</p> <p>Assuming <code>is_main_query() = FALSE</code> in this template file, how can I (1) determine which query I <em>am</em> looping within; and (2) access the non-main query's properties and methods?</p> <hr> <p>Example:</p> <h2><strong><code>page.php</code></strong></h2> <pre><code>&lt;?php $two_posts = new WP_Query(array( 'nopaging' =&gt; true, 'post_per_page' =&gt; -1, 'post_type' =&gt; 'post', 'post__in' =&gt; array(1, 2), 'orderby' =&gt; 'post__in' )); ?&gt; &lt;?php if($two_posts-&gt;have_posts()) : ?&gt; &lt;div class="two-posts"&gt; &lt;?php while($two_posts-&gt;have_posts()) : ?&gt; &lt;?php $two_posts-&gt;the_post(); ?&gt; &lt;?php get_template_part('templates/content', 'existing'); ?&gt; &lt;!-- or --&gt; &lt;?php include(locate_template('templates/content-existing.php')); ?&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code></pre> <h2><strong><code>templates/content-existing.php</code></strong></h2> <pre><code>&lt;?php if(is_main_query()) : ?&gt; &lt;p class="title"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;?php elseif(/* query == $two_posts */) : ?&gt; &lt;?php if(/* $two_posts-&gt;current_post == 0 */) : ?&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;h1&gt; &lt;?php endif; ?&gt; &lt;?php if(/* $two_posts-&gt;current_post == 1 */) : ?&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;?php endif; ?&gt; &lt;?php else : ?&gt; &lt;p&gt;Nothing to display here.&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 181120, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>First, <strong>don't use <code>is_main_query()</code> function</strong> (method is ok). It tells something absolutely different from what you would think it does — was the main query overridden.</p>\n\n<p>As far as I remember, there is no clean solution to this since WP doesn't have a concept of explicitly passing context to a specific template or template part.</p>\n\n<p>Since WP's way hinges primarily on globals, the “fitting” (if dirty) approach might be to pass the information in same fashion — through a global variable(s) of your own.</p>\n" }, { "answer_id": 181223, "author": "cfx", "author_id": 28957, "author_profile": "https://wordpress.stackexchange.com/users/28957", "pm_score": 1, "selected": true, "text": "<p>Thanks to Rarst's guidance I put together a quick solution that seems to do the trick even though it seems a bit hacky.</p>\n\n<hr>\n\n<p>Solution:</p>\n\n<h2><strong><code>page.php</code></strong></h2>\n\n<pre><code>&lt;?php\n $two_posts = new WP_Query(array(\n 'nopaging' =&gt; true,\n 'post_per_page' =&gt; -1,\n 'post_type' =&gt; 'post',\n 'post__in' =&gt; array(1, 2),\n 'orderby' =&gt; 'post__in'\n ));\n\n /* Setup default global query boolean */\n $GLOBALS['two_posts_query'] = FALSE;\n\n /* Keep track of the post count */\n $GLOBALS['two_posts_count'] = $two_posts-&gt;post_count;\n?&gt;\n\n&lt;?php if($two_posts-&gt;have_posts()) : ?&gt;\n &lt;div class=\"two-posts\"&gt;\n &lt;?php while($two_posts-&gt;have_posts()) : ?&gt;\n &lt;?php $two_posts-&gt;the_post(); ?&gt;\n &lt;?php /* Keep track of the current post */ ?&gt;\n &lt;?php $GLOBALS['two_posts_current_post'] = $two_posts-&gt;current_post; ?&gt;\n &lt;?php /* Set global variable to TRUE */ ?&gt;\n &lt;?php $GLOBALS['two_posts_query'] = TRUE; ?&gt;\n &lt;?php get_template_part('templates/content', 'existing'); ?&gt;\n &lt;?php $GLOBALS['two_posts_query'] = FALSE; ?&gt;\n &lt;?php /* Reset global variable to FALSE */ ?&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/div&gt;\n&lt;?php endif; ?&gt;\n&lt;?php wp_reset_query(); ?&gt;\n</code></pre>\n\n<h2><strong><code>templates/content-existing.php</code></strong></h2>\n\n<pre><code>&lt;?php\n global $two_posts_query, $two_posts_post_count, $two_posts_current_post;\n?&gt;\n\n&lt;?php if($two_posts_query &amp;&amp; $two_posts_post_count &gt;= 2) : ?&gt;\n &lt;?php if($two_posts_current_post == 0) : ?&gt;\n &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;h1&gt;\n &lt;?php elseif($two_posts_current_post &gt; 0) : ?&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;?php endif; ?&gt;\n&lt;?php else : ?&gt;\n &lt;p class=\"title\"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28957/" ]
Sometimes there's no way around creating a custom query, but when I do and then loop through it, I often want to use `get_template_part()` within the custom query loop to pull in a template I already know will fit my needs. Sometimes that template is 99.9% perfect and only needs some conditionals added for it to behave as needed depending on the query. Assuming `is_main_query() = FALSE` in this template file, how can I (1) determine which query I *am* looping within; and (2) access the non-main query's properties and methods? --- Example: **`page.php`** -------------- ``` <?php $two_posts = new WP_Query(array( 'nopaging' => true, 'post_per_page' => -1, 'post_type' => 'post', 'post__in' => array(1, 2), 'orderby' => 'post__in' )); ?> <?php if($two_posts->have_posts()) : ?> <div class="two-posts"> <?php while($two_posts->have_posts()) : ?> <?php $two_posts->the_post(); ?> <?php get_template_part('templates/content', 'existing'); ?> <!-- or --> <?php include(locate_template('templates/content-existing.php')); ?> <?php endwhile; ?> </div> <?php endif; ?> <?php wp_reset_query(); ?> ``` **`templates/content-existing.php`** ------------------------------------ ``` <?php if(is_main_query()) : ?> <p class="title"><?php the_title(); ?></p> <?php elseif(/* query == $two_posts */) : ?> <?php if(/* $two_posts->current_post == 0 */) : ?> <h1><?php the_title(); ?><h1> <?php endif; ?> <?php if(/* $two_posts->current_post == 1 */) : ?> <h2><?php the_title(); ?></h2> <?php endif; ?> <?php else : ?> <p>Nothing to display here.</p> <?php endif; ?> ```
Thanks to Rarst's guidance I put together a quick solution that seems to do the trick even though it seems a bit hacky. --- Solution: **`page.php`** -------------- ``` <?php $two_posts = new WP_Query(array( 'nopaging' => true, 'post_per_page' => -1, 'post_type' => 'post', 'post__in' => array(1, 2), 'orderby' => 'post__in' )); /* Setup default global query boolean */ $GLOBALS['two_posts_query'] = FALSE; /* Keep track of the post count */ $GLOBALS['two_posts_count'] = $two_posts->post_count; ?> <?php if($two_posts->have_posts()) : ?> <div class="two-posts"> <?php while($two_posts->have_posts()) : ?> <?php $two_posts->the_post(); ?> <?php /* Keep track of the current post */ ?> <?php $GLOBALS['two_posts_current_post'] = $two_posts->current_post; ?> <?php /* Set global variable to TRUE */ ?> <?php $GLOBALS['two_posts_query'] = TRUE; ?> <?php get_template_part('templates/content', 'existing'); ?> <?php $GLOBALS['two_posts_query'] = FALSE; ?> <?php /* Reset global variable to FALSE */ ?> <?php endwhile; ?> </div> <?php endif; ?> <?php wp_reset_query(); ?> ``` **`templates/content-existing.php`** ------------------------------------ ``` <?php global $two_posts_query, $two_posts_post_count, $two_posts_current_post; ?> <?php if($two_posts_query && $two_posts_post_count >= 2) : ?> <?php if($two_posts_current_post == 0) : ?> <h1><?php the_title(); ?><h1> <?php elseif($two_posts_current_post > 0) : ?> <h2><?php the_title(); ?></h2> <?php endif; ?> <?php else : ?> <p class="title"><?php the_title(); ?></p> <?php endif; ?> ```
181,122
<p>I've been browsing through similar questions and have yet to get this functionality to work. I'm tracking the progress a user makes an embedded vimeo video and insert data or update data.</p> <p>JS on the post page:</p> <pre><code> $.ajax({ type: 'POST', dataType: 'json', url: ajaxurl, data: { 'action': 'vimeo_progress', 'progress_percent': progress, 'progress_seconds': seconds, 'course_id': courseID }, success : function(data) { console.log(data); //FOR DEBUG }, error : function(data, textStatus, XMLHttpRequest) { console.log('updateProgress failed!'); //FOR DEBUG console.log(textStatus); //FOR DEBUG } }); </code></pre> <p>functions.php</p> <pre><code> add_action( 'wp_ajax_nopriv_vimeo_progress', 'store_vimeo_progress_callback' ); function store_vimeo_progress_callback() { // don't track if user is not logged in if ( ! is_user_logged_in() ) return false; $user_id = get_current_user_id(); $vimeo_percent = sanitize_text_field($_POST['progress_percent']); $vimeo_seconds = sanitize_text_field($_POST['progress_seconds']); $xxx_course_id = sanitize_text_field($_POST['course_id']); $table_name = $wpdb-&gt;prefix . "course_video_progress"; // Run WP query to retrieve user progress $row = $wpdb-&gt;get_row( $wpdb-&gt;prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $xxx_course_id) ); if ($row) { $wpdb-&gt;replace( $table_name, array( 'id' =&gt; $row-&gt;id, 'user_id' =&gt; $user_id, 'course_id' =&gt; $xxx_course_id, 'progress_percent' =&gt; $vimeo_percent, 'seconds_played' =&gt; $vimeo_seconds ), array( '%d', '%d', '%f', '%d' ) ); } else { $wpdb-&gt;insert( $table_name, array( 'user_id' =&gt; $user_id, 'course_id' =&gt; $xxx_course_id, 'progress_percent' =&gt; $vimeo_percent, 'seconds_played' =&gt; $vimeo_seconds ), array( '%d', '%d', '%f', '%d' ) ); } $response = array( 'success' =&gt; true, 'data' =&gt; 'hello' ); //if $data is set wp_send_json_success( $response ); exit; } </code></pre> <p>No data is ever inserted into table and no data is ever updated. I do get a "success" from callback but the data is returned as 0.</p> <p>edit: I just realized <a href="http://localhost/wordpress/wp-admin/admin-ajax.php" rel="nofollow">http://localhost/wordpress/wp-admin/admin-ajax.php</a> returns 0 so maybe the ajax call is not even finding my function and simply returning 0?</p>
[ { "answer_id": 181137, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I'm not entirely sure you want to call exit at the end of that function, since exit terminates all further PHP execution. This is likely the cause of your troubles.</p>\n\n<p><a href=\"http://php.net/manual/en/function.exit.php\" rel=\"nofollow\">http://php.net/manual/en/function.exit.php</a></p>\n\n<p>That said, you can always test for the result of your queries by setting a variable to be the result, and then sending that as your $response.</p>\n\n<pre><code>if ($row) {\n $qry_result = $wpdb-&gt;replace( \n $table_name, \n array( \n 'id' =&gt; $row-&gt;id,\n 'user_id' =&gt; $user_id, \n 'course_id' =&gt; $xxx_course_id,\n 'progress_percent' =&gt; $vimeo_percent,\n 'seconds_played' =&gt; $vimeo_seconds\n ), \n array( \n '%d',\n '%d',\n '%f', \n '%d' \n ) \n );\n} else {\n $qry_result = $wpdb-&gt;insert( \n $table_name, \n array( \n 'user_id' =&gt; $user_id, \n 'course_id' =&gt; $xxx_course_id,\n 'progress_percent' =&gt; $vimeo_percent,\n 'seconds_played' =&gt; $vimeo_seconds\n ), \n array( \n '%d',\n '%d',\n '%f', \n '%d' \n ) \n );\n}\n\nif( false !== $qry_result ) {\n $qry_result = true;\n}\n\n$response = array( 'success' =&gt; $qry_result, 'data' =&gt; 'hello' ); //if $data is set\nwp_send_json_success( $response );\n</code></pre>\n" }, { "answer_id": 181235, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 1, "selected": false, "text": "<p>If you omit the <code>datatype</code> parameter from your AJAX call in your JS section of code jQuery will attempt to determine the datatype of the response from the server. While you're debugging this can be helpful as you can simply <code>echo</code> values from your AJAX callback in PHP. You can read the results in your <code>console.log()</code> statements. </p>\n\n<p>An alternative is to enable the <code>WP_DEBUG_LOG</code> constant in your <code>wp-config.php</code> file. Then you can call the <code>error_log()</code> function in PHP which will log the response to the <code>debug.log</code> file in your <code>/wp-content/</code>folder of your site. See <a href=\"http://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_LOG\" rel=\"nofollow\">http://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_LOG</a></p>\n\n<p>Those two tips should help you debug what is going on with your AJAX callback. </p>\n" }, { "answer_id": 207972, "author": "mrbobbybryant", "author_id": 64953, "author_profile": "https://wordpress.stackexchange.com/users/64953", "pm_score": 0, "selected": false, "text": "<p>Another tip I would give is to make use of wp_send_json_error(). <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json_error\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_send_json_error</a></p>\n\n<p>That way you can pass messages if things go wrong. And these json messages will show up when you hit the endpoint directly. For example, if you have a user permissions check, if they do not have permission output \n<code>wp_send_json_error('you do not have permission to do this')</code>\nOr something like that.</p>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69034/" ]
I've been browsing through similar questions and have yet to get this functionality to work. I'm tracking the progress a user makes an embedded vimeo video and insert data or update data. JS on the post page: ``` $.ajax({ type: 'POST', dataType: 'json', url: ajaxurl, data: { 'action': 'vimeo_progress', 'progress_percent': progress, 'progress_seconds': seconds, 'course_id': courseID }, success : function(data) { console.log(data); //FOR DEBUG }, error : function(data, textStatus, XMLHttpRequest) { console.log('updateProgress failed!'); //FOR DEBUG console.log(textStatus); //FOR DEBUG } }); ``` functions.php ``` add_action( 'wp_ajax_nopriv_vimeo_progress', 'store_vimeo_progress_callback' ); function store_vimeo_progress_callback() { // don't track if user is not logged in if ( ! is_user_logged_in() ) return false; $user_id = get_current_user_id(); $vimeo_percent = sanitize_text_field($_POST['progress_percent']); $vimeo_seconds = sanitize_text_field($_POST['progress_seconds']); $xxx_course_id = sanitize_text_field($_POST['course_id']); $table_name = $wpdb->prefix . "course_video_progress"; // Run WP query to retrieve user progress $row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $xxx_course_id) ); if ($row) { $wpdb->replace( $table_name, array( 'id' => $row->id, 'user_id' => $user_id, 'course_id' => $xxx_course_id, 'progress_percent' => $vimeo_percent, 'seconds_played' => $vimeo_seconds ), array( '%d', '%d', '%f', '%d' ) ); } else { $wpdb->insert( $table_name, array( 'user_id' => $user_id, 'course_id' => $xxx_course_id, 'progress_percent' => $vimeo_percent, 'seconds_played' => $vimeo_seconds ), array( '%d', '%d', '%f', '%d' ) ); } $response = array( 'success' => true, 'data' => 'hello' ); //if $data is set wp_send_json_success( $response ); exit; } ``` No data is ever inserted into table and no data is ever updated. I do get a "success" from callback but the data is returned as 0. edit: I just realized <http://localhost/wordpress/wp-admin/admin-ajax.php> returns 0 so maybe the ajax call is not even finding my function and simply returning 0?
I'm not entirely sure you want to call exit at the end of that function, since exit terminates all further PHP execution. This is likely the cause of your troubles. <http://php.net/manual/en/function.exit.php> That said, you can always test for the result of your queries by setting a variable to be the result, and then sending that as your $response. ``` if ($row) { $qry_result = $wpdb->replace( $table_name, array( 'id' => $row->id, 'user_id' => $user_id, 'course_id' => $xxx_course_id, 'progress_percent' => $vimeo_percent, 'seconds_played' => $vimeo_seconds ), array( '%d', '%d', '%f', '%d' ) ); } else { $qry_result = $wpdb->insert( $table_name, array( 'user_id' => $user_id, 'course_id' => $xxx_course_id, 'progress_percent' => $vimeo_percent, 'seconds_played' => $vimeo_seconds ), array( '%d', '%d', '%f', '%d' ) ); } if( false !== $qry_result ) { $qry_result = true; } $response = array( 'success' => $qry_result, 'data' => 'hello' ); //if $data is set wp_send_json_success( $response ); ```
181,134
<p>I have just set up a post/parent relationship between a post type "episodes" and a post type "cartoon-series."</p> <p>I used this bit of code to add in the meta box to assign the parent from another post type:</p> <pre><code>add_action('admin_menu', function() { remove_meta_box('pageparentdiv', 'episodes', 'normal'); }); add_action('add_meta_boxes', function() { add_meta_box('episodes-parent', 'Cartoon Series', 'episodes_attributes_meta_box', 'episodes', 'side', 'default'); }); function episodes_attributes_meta_box($post) { $post_type_object = get_post_type_object($post-&gt;post_type); if ( $post_type_object-&gt;hierarchical ) { $pages = wp_dropdown_pages(array('post_type' =&gt; 'cartoon-series', 'selected' =&gt; $post-&gt;post_parent, 'name' =&gt; 'parent_id', 'show_option_none' =&gt; __('(no parent)'), 'sort_column'=&gt; 'menu_order, post_title', 'echo' =&gt; 0)); if ( ! empty($pages) ) { echo $pages; } // end empty pages check } // end hierarchical check. } </code></pre> <p>That worked on the admin screen in allowing me to set the series as a parent to the episode, but when I try to view the post, I get a 404. The url structure is:</p> <pre><code>domain/episodes/series-name/episode-name </code></pre> <p>The url for the series is:</p> <pre><code>domain/cartoon-series/series-name </code></pre> <p>I'd like the url for the episode to be:</p> <pre><code>domain/cartoon-series/series-name/episode-name </code></pre> <p>What am I missing? Is it possible to make an entire post type the child of another post type? So, then I could even get the url for the episodes list to be:</p> <pre><code>domain/cartoon-series/series-name/episodes </code></pre> <p>Thanks! Matt</p> <hr> <p>As requested, here is the code for the two custom post types in question:</p> <pre><code>$labels = array( "name" =&gt; "Cartoon Series", "singular_name" =&gt; "Cartoon Series", "menu_name" =&gt; "Cartoon Series", "all_items" =&gt; "All Cartoon Series", "add_new" =&gt; "Add New", "add_new_item" =&gt; "Add New Cartoon Series", "edit" =&gt; "Edit", "edit_item" =&gt; "Edit Cartoon Series", "new_item" =&gt; "New Cartoon Series", "view" =&gt; "View", "view_item" =&gt; "View Cartoon Series", "search_items" =&gt; "Search Cartoon Series", "not_found" =&gt; "No Cartoon Series Found", "not_found_in_trash" =&gt; "No Cartoon Series Found in Trash", "parent" =&gt; "Parent Cartoon Series", ); $args = array( "labels" =&gt; $labels, "description" =&gt; "", "public" =&gt; true, "show_ui" =&gt; true, "has_archive" =&gt; true, "show_in_menu" =&gt; true, "exclude_from_search" =&gt; false, "capability_type" =&gt; "post", "map_meta_cap" =&gt; true, "hierarchical" =&gt; true, "rewrite" =&gt; array( "slug" =&gt; "cartoon-series", "with_front" =&gt; true ), "query_var" =&gt; true, "supports" =&gt; array( "title", "revisions", "thumbnail" ), ); register_post_type( "cartoon-series", $args ); $labels = array( "name" =&gt; "Episodes", "singular_name" =&gt; "Episode", ); $args = array( "labels" =&gt; $labels, "description" =&gt; "", "public" =&gt; true, "show_ui" =&gt; true, "has_archive" =&gt; true, "show_in_menu" =&gt; true, "exclude_from_search" =&gt; false, "capability_type" =&gt; "post", "map_meta_cap" =&gt; true, "hierarchical" =&gt; true, "rewrite" =&gt; array( "slug" =&gt; "episodes", "with_front" =&gt; true ), "query_var" =&gt; true, "supports" =&gt; array( "title", "revisions", "thumbnail" ), ); register_post_type( "episodes", $args ); </code></pre> <p>I'm using the CPT UI plugin, so I can't edit that code directly. That is just the export code CPT UI provides.</p> <p>I don't have any other code that links the two CPTs. Maybe that's what I'm missing. I just found that code online that places the metabox on the page to do the linking. Is it not enough to do the job? Looks like it sets the post_parent.</p> <p>Thanks! Matt</p>
[ { "answer_id": 181202, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>You will need to write your own URL parsing code for that as wordpress needs to know the type of the post it tries to retrieve from the DB based on the url structure and your url structure do no give any hint to this. </p>\n\n<p>This is not something that is very easy to do with the rewrite rules API of wordpress, but there is nothing that prevents you bypassing the rewrite mechanism and parsing the urls by yourself. Something like\n1. run wordpress rewite rules. If a content was found display it and exit\n2. get the first part of the url, check if there is a post matching that slug with the expected post type\n3. loop on the rest parts of the URL verify that the posts exist and are in the right type.\n4. if everything matches display the last post found, else display a 404 page</p>\n" }, { "answer_id": 181204, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 5, "selected": true, "text": "<p>Finally I've found a working solution. The cartoon-series can be registered as you did but episodes custom post types can not be hirarchical (I think WordPress expects parent content be the same type as child content if the relationship is set using <code>post_parent</code> in <code>wp_posts</code> database table).</p>\n\n<p>When registering episodes, the rewrite rule must be set to the slug you want, that is <code>cartoon-series/%series_name%</code>. Then we can filter the episodes link to replace <code>%series_name%</code> with actual name of the parent <code>cartoon-series</code> post type and a rewrite rule to say to WordPress when a cartoon-series post type is requested and when is a episodes.</p>\n\n<pre><code>add_action('init', function(){\n $labels = array(\n \"name\" =&gt; \"Cartoon Series\",\n \"singular_name\" =&gt; \"Cartoon Series\",\n \"menu_name\" =&gt; \"Cartoon Series\",\n \"all_items\" =&gt; \"All Cartoon Series\",\n \"add_new\" =&gt; \"Add New\",\n \"add_new_item\" =&gt; \"Add New Cartoon Series\",\n \"edit\" =&gt; \"Edit\",\n \"edit_item\" =&gt; \"Edit Cartoon Series\",\n \"new_item\" =&gt; \"New Cartoon Series\",\n \"view\" =&gt; \"View\",\n \"view_item\" =&gt; \"View Cartoon Series\",\n \"search_items\" =&gt; \"Search Cartoon Series\",\n \"not_found\" =&gt; \"No Cartoon Series Found\",\n \"not_found_in_trash\" =&gt; \"No Cartoon Series Found in Trash\",\n \"parent\" =&gt; \"Parent Cartoon Series\",\n );\n\n $args = array(\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"has_archive\" =&gt; true,\n \"show_in_menu\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; true,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"cartoon-series\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"revisions\", \"thumbnail\" )\n );\n\n register_post_type( \"cartoon-series\", $args );\n\n $labels = array(\n \"name\" =&gt; \"Episodes\",\n \"singular_name\" =&gt; \"Episode\",\n );\n\n $args = array(\n \"labels\" =&gt; $labels,\n \"description\" =&gt; \"\",\n \"public\" =&gt; true,\n \"show_ui\" =&gt; true,\n \"has_archive\" =&gt; true,\n \"show_in_menu\" =&gt; true,\n \"exclude_from_search\" =&gt; false,\n \"capability_type\" =&gt; \"post\",\n \"map_meta_cap\" =&gt; true,\n \"hierarchical\" =&gt; false,\n \"rewrite\" =&gt; array( \"slug\" =&gt; \"cartoon-series/%series_name%\", \"with_front\" =&gt; true ),\n \"query_var\" =&gt; true,\n \"supports\" =&gt; array( \"title\", \"revisions\", \"thumbnail\" )\n );\n\n register_post_type( \"episodes\", $args );\n\n});\n\nadd_action('add_meta_boxes', function() {\n add_meta_box('episodes-parent', 'Cartoon Series', 'episodes_attributes_meta_box', 'episodes', 'side', 'default');\n});\n\nfunction episodes_attributes_meta_box($post) {\n $pages = wp_dropdown_pages(array('post_type' =&gt; 'cartoon-series', 'selected' =&gt; $post-&gt;post_parent, 'name' =&gt; 'parent_id', 'show_option_none' =&gt; __('(no parent)'), 'sort_column'=&gt; 'menu_order, post_title', 'echo' =&gt; 0));\n if ( ! empty($pages) ) {\n echo $pages;\n } // end empty pages check\n}\n\nadd_action( 'init', function() {\n\n add_rewrite_rule( '^cartoon-series/(.*)/([^/]+)/?$','index.php?episodes=$matches[2]','top' );\n\n});\n\nadd_filter( 'post_type_link', function( $link, $post ) {\n if ( 'episodes' == get_post_type( $post ) ) {\n //Lets go to get the parent cartoon-series name\n if( $post-&gt;post_parent ) {\n $parent = get_post( $post-&gt;post_parent );\n if( !empty($parent-&gt;post_name) ) {\n return str_replace( '%series_name%', $parent-&gt;post_name, $link );\n }\n } else {\n //This seems to not work. It is intented to build pretty permalinks\n //when episodes has not parent, but it seems that it would need\n //additional rewrite rules\n //return str_replace( '/%series_name%', '', $link );\n }\n\n }\n return $link;\n}, 10, 2 );\n</code></pre>\n\n<p><strong>NOTE</strong>: Remember to flush rewrite rules after saving the above code and before to try it. Go to <code>wp-admin/options-permalink.php</code> and click save to regerenate the rewrite rules.</p>\n\n<p><strong>NOTE 2</strong>: It is probably that more rewrite rules have to be added, for example to work for paginate posts. Also it may need some more work in order to have a complete solution, for example, when deleting a <code>cartoon-series</code> delete also all child episodes? Add a filter in admin edit screen to filter episodes by post parent? Modify the episodes title in admin edit screen to show the parent series name?</p>\n" }, { "answer_id": 255488, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 1, "selected": false, "text": "<p>No need for hard-coding in this case, you can simply use this plugin:</p>\n<p><a href=\"https://wordpress.org/plugins/add-hierarchy-parent-to-post/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/add-hierarchy-parent-to-post/</a></p>\n<p>You can even grab code from it. However, it may not be a full solution.</p>\n" } ]
2015/03/13
[ "https://wordpress.stackexchange.com/questions/181134", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68905/" ]
I have just set up a post/parent relationship between a post type "episodes" and a post type "cartoon-series." I used this bit of code to add in the meta box to assign the parent from another post type: ``` add_action('admin_menu', function() { remove_meta_box('pageparentdiv', 'episodes', 'normal'); }); add_action('add_meta_boxes', function() { add_meta_box('episodes-parent', 'Cartoon Series', 'episodes_attributes_meta_box', 'episodes', 'side', 'default'); }); function episodes_attributes_meta_box($post) { $post_type_object = get_post_type_object($post->post_type); if ( $post_type_object->hierarchical ) { $pages = wp_dropdown_pages(array('post_type' => 'cartoon-series', 'selected' => $post->post_parent, 'name' => 'parent_id', 'show_option_none' => __('(no parent)'), 'sort_column'=> 'menu_order, post_title', 'echo' => 0)); if ( ! empty($pages) ) { echo $pages; } // end empty pages check } // end hierarchical check. } ``` That worked on the admin screen in allowing me to set the series as a parent to the episode, but when I try to view the post, I get a 404. The url structure is: ``` domain/episodes/series-name/episode-name ``` The url for the series is: ``` domain/cartoon-series/series-name ``` I'd like the url for the episode to be: ``` domain/cartoon-series/series-name/episode-name ``` What am I missing? Is it possible to make an entire post type the child of another post type? So, then I could even get the url for the episodes list to be: ``` domain/cartoon-series/series-name/episodes ``` Thanks! Matt --- As requested, here is the code for the two custom post types in question: ``` $labels = array( "name" => "Cartoon Series", "singular_name" => "Cartoon Series", "menu_name" => "Cartoon Series", "all_items" => "All Cartoon Series", "add_new" => "Add New", "add_new_item" => "Add New Cartoon Series", "edit" => "Edit", "edit_item" => "Edit Cartoon Series", "new_item" => "New Cartoon Series", "view" => "View", "view_item" => "View Cartoon Series", "search_items" => "Search Cartoon Series", "not_found" => "No Cartoon Series Found", "not_found_in_trash" => "No Cartoon Series Found in Trash", "parent" => "Parent Cartoon Series", ); $args = array( "labels" => $labels, "description" => "", "public" => true, "show_ui" => true, "has_archive" => true, "show_in_menu" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => true, "rewrite" => array( "slug" => "cartoon-series", "with_front" => true ), "query_var" => true, "supports" => array( "title", "revisions", "thumbnail" ), ); register_post_type( "cartoon-series", $args ); $labels = array( "name" => "Episodes", "singular_name" => "Episode", ); $args = array( "labels" => $labels, "description" => "", "public" => true, "show_ui" => true, "has_archive" => true, "show_in_menu" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => true, "rewrite" => array( "slug" => "episodes", "with_front" => true ), "query_var" => true, "supports" => array( "title", "revisions", "thumbnail" ), ); register_post_type( "episodes", $args ); ``` I'm using the CPT UI plugin, so I can't edit that code directly. That is just the export code CPT UI provides. I don't have any other code that links the two CPTs. Maybe that's what I'm missing. I just found that code online that places the metabox on the page to do the linking. Is it not enough to do the job? Looks like it sets the post\_parent. Thanks! Matt
Finally I've found a working solution. The cartoon-series can be registered as you did but episodes custom post types can not be hirarchical (I think WordPress expects parent content be the same type as child content if the relationship is set using `post_parent` in `wp_posts` database table). When registering episodes, the rewrite rule must be set to the slug you want, that is `cartoon-series/%series_name%`. Then we can filter the episodes link to replace `%series_name%` with actual name of the parent `cartoon-series` post type and a rewrite rule to say to WordPress when a cartoon-series post type is requested and when is a episodes. ``` add_action('init', function(){ $labels = array( "name" => "Cartoon Series", "singular_name" => "Cartoon Series", "menu_name" => "Cartoon Series", "all_items" => "All Cartoon Series", "add_new" => "Add New", "add_new_item" => "Add New Cartoon Series", "edit" => "Edit", "edit_item" => "Edit Cartoon Series", "new_item" => "New Cartoon Series", "view" => "View", "view_item" => "View Cartoon Series", "search_items" => "Search Cartoon Series", "not_found" => "No Cartoon Series Found", "not_found_in_trash" => "No Cartoon Series Found in Trash", "parent" => "Parent Cartoon Series", ); $args = array( "labels" => $labels, "description" => "", "public" => true, "show_ui" => true, "has_archive" => true, "show_in_menu" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => true, "rewrite" => array( "slug" => "cartoon-series", "with_front" => true ), "query_var" => true, "supports" => array( "title", "revisions", "thumbnail" ) ); register_post_type( "cartoon-series", $args ); $labels = array( "name" => "Episodes", "singular_name" => "Episode", ); $args = array( "labels" => $labels, "description" => "", "public" => true, "show_ui" => true, "has_archive" => true, "show_in_menu" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "cartoon-series/%series_name%", "with_front" => true ), "query_var" => true, "supports" => array( "title", "revisions", "thumbnail" ) ); register_post_type( "episodes", $args ); }); add_action('add_meta_boxes', function() { add_meta_box('episodes-parent', 'Cartoon Series', 'episodes_attributes_meta_box', 'episodes', 'side', 'default'); }); function episodes_attributes_meta_box($post) { $pages = wp_dropdown_pages(array('post_type' => 'cartoon-series', 'selected' => $post->post_parent, 'name' => 'parent_id', 'show_option_none' => __('(no parent)'), 'sort_column'=> 'menu_order, post_title', 'echo' => 0)); if ( ! empty($pages) ) { echo $pages; } // end empty pages check } add_action( 'init', function() { add_rewrite_rule( '^cartoon-series/(.*)/([^/]+)/?$','index.php?episodes=$matches[2]','top' ); }); add_filter( 'post_type_link', function( $link, $post ) { if ( 'episodes' == get_post_type( $post ) ) { //Lets go to get the parent cartoon-series name if( $post->post_parent ) { $parent = get_post( $post->post_parent ); if( !empty($parent->post_name) ) { return str_replace( '%series_name%', $parent->post_name, $link ); } } else { //This seems to not work. It is intented to build pretty permalinks //when episodes has not parent, but it seems that it would need //additional rewrite rules //return str_replace( '/%series_name%', '', $link ); } } return $link; }, 10, 2 ); ``` **NOTE**: Remember to flush rewrite rules after saving the above code and before to try it. Go to `wp-admin/options-permalink.php` and click save to regerenate the rewrite rules. **NOTE 2**: It is probably that more rewrite rules have to be added, for example to work for paginate posts. Also it may need some more work in order to have a complete solution, for example, when deleting a `cartoon-series` delete also all child episodes? Add a filter in admin edit screen to filter episodes by post parent? Modify the episodes title in admin edit screen to show the parent series name?
181,142
<p>I have a post type <code>gtre</code> and metadata <code>price</code>.</p> <p>The 'price' metadata I get using <code>get_post_meta($post-&gt;ID, 'key', true)["price"];</code></p> <p>So I don´t know how exactly should I write the args for <code>WP_Query</code> constructor, so I can get the posts in order by the '<code>price</code>' meta data. I mean I want the query to ordered by '<code>price</code>'.</p> <p>I have tried this:</p> <pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $temp = $wp_query; $wp_query = NULL; $args = array('post_type' =&gt; 'gtre', 'posts_per_page'=&gt;'6', 'order'=&gt;'ASC', 'page'=&gt;$paged, 'meta_query' =&gt; array( 'key' =&gt; 'price', ), 'orderby'=&gt;'meta_value'); $wp_query = new WP_Query($args); </code></pre> <p>But I only get the posts in '<code>ASC</code>' order by time of posting.</p> <p>How could be my '<code>$args</code>' array so I can sort or order by the '<code>price</code>' meta data. And this '<code>price</code>' meta data I only get if I use '<code>get_post_meta($post-&gt;ID, 'key', true)["price"]</code>', I mean I can only get the price by using the function '<code>get_post_meta</code>'.</p> <p>Any help? Thanks.</p>
[ { "answer_id": 181144, "author": "Brad Elsmore", "author_id": 69036, "author_profile": "https://wordpress.stackexchange.com/users/69036", "pm_score": 1, "selected": false, "text": "<p>I have achieved this in the past by using the following method.</p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; \n$args = array(\n 'post_type' =&gt; 'gtre',\n 'posts_per_page' =&gt; 6,\n 'paged' =&gt; $paged,\n 'meta_key' =&gt; 'price',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'ASC',\n);\n$pquery = new WP_Query($args);\n</code></pre>\n\n<p>There shouldn't be a need for the following in your code If you don't set the new query object to $wp_query.</p>\n\n<pre><code>$temp = $wp_query; \n$wp_query = NULL;\n</code></pre>\n\n<p>You generally don't want to alter that because it's the main query variable. By using a unique variable that isn't already being used for WordPress you can be sure this is only effecting the current query you're working on. Thus you won't have any unexpected results.</p>\n" }, { "answer_id": 181145, "author": "Marcelo Noronha", "author_id": 30777, "author_profile": "https://wordpress.stackexchange.com/users/30777", "pm_score": 0, "selected": false, "text": "<p>The issue in my question is because in the wordpress database the meta key \"price\", is as \"_price\", so adding an underline in 'price' I got it working. Thanks.</p>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181142", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69044/" ]
I have a post type `gtre` and metadata `price`. The 'price' metadata I get using `get_post_meta($post->ID, 'key', true)["price"];` So I don´t know how exactly should I write the args for `WP_Query` constructor, so I can get the posts in order by the '`price`' meta data. I mean I want the query to ordered by '`price`'. I have tried this: ``` $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $temp = $wp_query; $wp_query = NULL; $args = array('post_type' => 'gtre', 'posts_per_page'=>'6', 'order'=>'ASC', 'page'=>$paged, 'meta_query' => array( 'key' => 'price', ), 'orderby'=>'meta_value'); $wp_query = new WP_Query($args); ``` But I only get the posts in '`ASC`' order by time of posting. How could be my '`$args`' array so I can sort or order by the '`price`' meta data. And this '`price`' meta data I only get if I use '`get_post_meta($post->ID, 'key', true)["price"]`', I mean I can only get the price by using the function '`get_post_meta`'. Any help? Thanks.
I have achieved this in the past by using the following method. ``` $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'gtre', 'posts_per_page' => 6, 'paged' => $paged, 'meta_key' => 'price', 'orderby' => 'meta_value_num', 'order' => 'ASC', ); $pquery = new WP_Query($args); ``` There shouldn't be a need for the following in your code If you don't set the new query object to $wp\_query. ``` $temp = $wp_query; $wp_query = NULL; ``` You generally don't want to alter that because it's the main query variable. By using a unique variable that isn't already being used for WordPress you can be sure this is only effecting the current query you're working on. Thus you won't have any unexpected results.
181,153
<p>How do I redirect this page URL, <code>http://localhost/wordpress_rnd/?page_id=2</code>, to the home URL, <code>http://localhost/wordpress_rnd/</code>, without using any plugins?</p>
[ { "answer_id": 181159, "author": "cristian.raiber", "author_id": 52524, "author_profile": "https://wordpress.stackexchange.com/users/52524", "pm_score": -1, "selected": false, "text": "<p>Locate page.php (assuming you've created it already). After this line <code>&lt;?php get_header(); ?&gt;</code> add the following code:</p>\n\n<pre><code>&lt;?php if(is_page('2')) {\n wp_redirect( home_url(), '302' ); \n} ?&gt;\n</code></pre>\n\n<p>In the code above, <code>is_page('2')</code> is actually the ID of your page as you've specified in your example.</p>\n" }, { "answer_id": 181165, "author": "paul", "author_id": 1000, "author_profile": "https://wordpress.stackexchange.com/users/1000", "pm_score": 0, "selected": false, "text": "<pre><code>add_action( 'init', function() {\n if ( 0 === stripos( $_SERVER['REQUEST_URI'], '/page_id=2' ) ) {\n\n wp_redirect( home_url(), 301 );\n exit;\n\n }\n}\n</code></pre>\n\n<p>Put this code in a mu-plugin or in your theme's functions.php file</p>\n" }, { "answer_id": 181174, "author": "Fiaz Husyn", "author_id": 62739, "author_profile": "https://wordpress.stackexchange.com/users/62739", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_redirect\" rel=\"nofollow\">WP_REDIRECT</a> is the function that you need to use for redirecting in wordpress. It can be used like :</p>\n\n<pre><code>wp_redirect( $location, $status );\nexit;\n//$location is required parameter. It is used to give the target url to which page will get redirected.\n//$status is optional. It is used to set status code. Default is 302\n</code></pre>\n\n<p>You can use this function to redirect users from one page to other. It should be placed in either functions.php or the template file which is being used to display the current page. Now to use it in your situation, simple place the following code at the bottom of your functions.php file</p>\n\n<pre><code>$redirectFromPageID = 2; //Redirect from Page having ID of 2\n$redirectTo = home_url(); //Redirect to Home URL\n\nif( is_page( $redirectFromPageID ) ){\n wp_redirect( $redirectTo );\n exit;\n}\n</code></pre>\n" }, { "answer_id": 181224, "author": "cfx", "author_id": 28957, "author_profile": "https://wordpress.stackexchange.com/users/28957", "pm_score": 4, "selected": false, "text": "<p>The correct way to do this is using the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"noreferrer\"><code>template_redirect</code></a> hook by adding a function to your <code>functions.php</code>:</p>\n\n<pre><code>function redirect_to_home() {\n if(!is_admin() &amp;&amp; is_page('2')) {\n wp_redirect(home_url());\n exit();\n }\n}\nadd_action('template_redirect', 'redirect_to_home');\n</code></pre>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51547/" ]
How do I redirect this page URL, `http://localhost/wordpress_rnd/?page_id=2`, to the home URL, `http://localhost/wordpress_rnd/`, without using any plugins?
The correct way to do this is using the [`template_redirect`](https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect) hook by adding a function to your `functions.php`: ``` function redirect_to_home() { if(!is_admin() && is_page('2')) { wp_redirect(home_url()); exit(); } } add_action('template_redirect', 'redirect_to_home'); ```
181,160
<p>I'm trying to set up a woocommerce custom product type so that its as minimal as possible - no options I don't specifically designate. </p> <p>Still, despite the declaration below, the custom product meta box still shows "shipping" shipping options. </p> <p>How do I get rid of the shipping options? And on that note, any other that I may wish to remove.</p> <pre><code>add_action('plugins_loaded', 'ss_create_custom_product_type'); function ss_create_custom_product_type() { // declare the product class class WC_Product_Wdm extends WC_Product { public function __construct($product) { $this-&gt;product_type = 'ss_stock_image'; $this-&gt;virtual = 'yes'; $this-&gt;downloadable = 'yes'; $this-&gt;manage_stock = 'no'; parent::__construct($product); // add additional functions here } } } </code></pre> <p><img src="https://i.stack.imgur.com/SwMme.jpg" alt="enter image description here"></p> <p>UPDATE: </p> <p>I've updated the class per suggestion. Yet I wonder why the code is not getting fired.</p> <pre><code>add_action('plugins_loaded', 'ss_create_custom_product_type'); function ss_create_custom_product_type() { // declare the product class class WC_Product_Wdm extends WC_Product { public function __construct($product) { $this-&gt;product_type = 'ss_stock_image'; add_filter('woocommerce_product_data_tabs', array($this, 'remove_tabs'), 10, 1); parent::__construct($product); } public function remove_tabs($tabs) { /** * The available tab array keys are: * * general * inventory * shipping * linked_product * attribute * variations * advanced */ unset($tabs['shipping']); return $tabs; } } } </code></pre>
[ { "answer_id": 181166, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 4, "selected": true, "text": "<p>Looking further into the WooCommerce source, they fortunately, provide a filter named <code>woocommerce_product_data_tabs</code> which will allow you to conditional unset tabs.</p>\n\n<p>I've provided an example below:</p>\n\n<pre><code>add_filter('woocommerce_product_data_tabs', function($tabs) {\n\n /**\n * The available tab array keys are:\n * \n * general\n * inventory\n * shipping\n * linked_product\n * attribute\n * variations\n * advanced\n */\n\n unset($tabs['shipping']);\n return $tabs;\n\n}, 10, 1);\n</code></pre>\n\n<p>You may also filter the product type drop down menu using the <code>product_type_selector</code> filter and also the product type options checkboxes using the <code>product_type_options</code> filter.</p>\n\n<p>Example:</p>\n\n<pre><code>add_filter('product_type_selector', function($product_type) {\n\n /**\n * The available product type selection array keys are:\n * \n * simple\n * grouped\n * external\n * variable\n */\n\n unset($product_type['variable']); //as an example...\n return $product_type;\n\n}, 10, 1);\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>add_filter('product_type_options', function($product_options) {\n\n /**\n * The available product type options array keys are:\n * \n * virtual\n * downloadable\n */\n\n unset($product_options['downloadable']); //as an example...\n return $product_options;\n\n}, 10, 1);\n</code></pre>\n\n<p>For your reference I found these filters by first looking at the <code>add_meta_boxes</code> method contained within the <code>WC_Admin_Meta_Boxes</code> class within <code>includes/admin/class-wc-admin-meta-boxes.php</code>;</p>\n\n<p>From there you will note that they add a meta box, whose id is, <code>woocommerce-product-data</code> and the callback of which is <code>WC_Meta_Box_Product_Data::output</code> found within <code>includes/admin/meta-boxes/class-wc-meta-box-product-data.php</code>. </p>\n\n<p>It is within this <code>output</code> method that the filters <code>woocommerce_product_data_tabs</code>, <code>product_type_selector</code> and <code>product_type_options</code> exist.</p>\n" }, { "answer_id": 181171, "author": "1Up", "author_id": 57524, "author_profile": "https://wordpress.stackexchange.com/users/57524", "pm_score": 0, "selected": false, "text": "<p>Actually @userabuser has the more complete answer, but to overcome this problem I was able to simply add a \"hide\" class this way:</p>\n\n<pre><code>add_filter('woocommerce_product_data_tabs', function($tabs) {\n\n array_push($tabs['shipping']['class'], 'hide_if_ss_stock_image');\n return $tabs;\n\n}, 10, 1);\n</code></pre>\n\n<p>Notice the <code>hide_if_ss_stock_image</code> class that is added. </p>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57524/" ]
I'm trying to set up a woocommerce custom product type so that its as minimal as possible - no options I don't specifically designate. Still, despite the declaration below, the custom product meta box still shows "shipping" shipping options. How do I get rid of the shipping options? And on that note, any other that I may wish to remove. ``` add_action('plugins_loaded', 'ss_create_custom_product_type'); function ss_create_custom_product_type() { // declare the product class class WC_Product_Wdm extends WC_Product { public function __construct($product) { $this->product_type = 'ss_stock_image'; $this->virtual = 'yes'; $this->downloadable = 'yes'; $this->manage_stock = 'no'; parent::__construct($product); // add additional functions here } } } ``` ![enter image description here](https://i.stack.imgur.com/SwMme.jpg) UPDATE: I've updated the class per suggestion. Yet I wonder why the code is not getting fired. ``` add_action('plugins_loaded', 'ss_create_custom_product_type'); function ss_create_custom_product_type() { // declare the product class class WC_Product_Wdm extends WC_Product { public function __construct($product) { $this->product_type = 'ss_stock_image'; add_filter('woocommerce_product_data_tabs', array($this, 'remove_tabs'), 10, 1); parent::__construct($product); } public function remove_tabs($tabs) { /** * The available tab array keys are: * * general * inventory * shipping * linked_product * attribute * variations * advanced */ unset($tabs['shipping']); return $tabs; } } } ```
Looking further into the WooCommerce source, they fortunately, provide a filter named `woocommerce_product_data_tabs` which will allow you to conditional unset tabs. I've provided an example below: ``` add_filter('woocommerce_product_data_tabs', function($tabs) { /** * The available tab array keys are: * * general * inventory * shipping * linked_product * attribute * variations * advanced */ unset($tabs['shipping']); return $tabs; }, 10, 1); ``` You may also filter the product type drop down menu using the `product_type_selector` filter and also the product type options checkboxes using the `product_type_options` filter. Example: ``` add_filter('product_type_selector', function($product_type) { /** * The available product type selection array keys are: * * simple * grouped * external * variable */ unset($product_type['variable']); //as an example... return $product_type; }, 10, 1); ``` Example: ``` add_filter('product_type_options', function($product_options) { /** * The available product type options array keys are: * * virtual * downloadable */ unset($product_options['downloadable']); //as an example... return $product_options; }, 10, 1); ``` For your reference I found these filters by first looking at the `add_meta_boxes` method contained within the `WC_Admin_Meta_Boxes` class within `includes/admin/class-wc-admin-meta-boxes.php`; From there you will note that they add a meta box, whose id is, `woocommerce-product-data` and the callback of which is `WC_Meta_Box_Product_Data::output` found within `includes/admin/meta-boxes/class-wc-meta-box-product-data.php`. It is within this `output` method that the filters `woocommerce_product_data_tabs`, `product_type_selector` and `product_type_options` exist.
181,182
<p>I have a category called <code>feature</code> which I use to have a feature post in the homepage. The problem is I don't want the category name <code>feature</code> to appear in this posts, but I want the other categories to show up.</p> <p>How could I do that?</p>
[ { "answer_id": 181186, "author": "Rahman Sharif", "author_id": 24483, "author_profile": "https://wordpress.stackexchange.com/users/24483", "pm_score": 3, "selected": true, "text": "<p>To achieve this we need to use <code>get_the_category</code> <a href=\"http://codex.wordpress.org/Function_Reference/get_the_category\" rel=\"nofollow\">here</a>.\nI am going to use this code in several places, so it is more efficient to create a function</p>\n\n<pre>\nfunction exclude_cats($excludedcats = array()){\n\n $categories = get_the_category();\n $separator = ', ';\n $output = '';\n foreach($categories as $category) {\n if ( !in_array($category->cat_ID, $excludedcats) ) {\n $output .= 'term_id ).'\" title=\"' . esc_attr( sprintf( __( \"View all posts in %s\" ), $category->name ) ) . '\">'.$category->cat_name.''.$separator;\n }\n }\n echo trim($output, $separator);\n\n}\n</pre>\n\n<p>All that I've done inside the function was to call <code>get_the_category</code> function, But I've excluded the categories I don't want to show their names to not show.</p>\n\n<p>inside the index I've called the function like so <code>exclude_cats(array(11, 40, 53));</code></p>\n" }, { "answer_id": 191837, "author": "Lafif Astahdziq", "author_id": 54707, "author_profile": "https://wordpress.stackexchange.com/users/54707", "pm_score": 0, "selected": false, "text": "<p>How about using <code>get_the_terms</code> filter like this,,</p>\n\n<pre><code>add_filter('get_the_terms', 'hide_categories_terms', 10, 3);\nfunction hide_categories_terms($terms, $post_id, $taxonomy){\n\n // get term to exclude by name, by id or maybe by slug\n $exclude = get_term_by('name', 'feature', 'category', ARRAY_A);\n\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == \"category\"){\n if(in_array($key, $exclude)) unset($terms[$key]);\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>i think it should works,,</p>\n" }, { "answer_id": 230921, "author": "Stefan Wimmer", "author_id": 97504, "author_profile": "https://wordpress.stackexchange.com/users/97504", "pm_score": 1, "selected": false, "text": "<p>I think @Lafif Astahdziq was on the right track - I like his approach even though it is fairly static. Here is how I rewrote it:</p>\n\n<pre><code>add_filter('get_the_terms', 'hide_categories_terms', 10, 3);\nfunction hide_categories_terms($terms, $post_id, $taxonomy){\n\n // define which category IDs you want to hide\n $excludeIDs = array(6);\n\n // get all the terms \n $exclude = array();\n foreach ($excludeIDs as $id) {\n $exclude[] = get_term_by('id', $id, 'category');\n }\n\n // filter the categories\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == \"category\"){\n foreach ($exclude as $exKey =&gt; $exTerm) {\n if($term-&gt;term_id == $exTerm-&gt;term_id) unset($terms[$key]);\n }\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>Put this in your functions.php and it will work.</p>\n" }, { "answer_id": 291167, "author": "Andy Gee", "author_id": 87583, "author_profile": "https://wordpress.stackexchange.com/users/87583", "pm_score": 0, "selected": false, "text": "<p>An old question but still quite popular so I have added another solution to add to your theme's functions.php file.</p>\n\n<pre><code>function hide_feature($query){\n if($query-&gt;is_main_query() &amp;&amp; $query-&gt;is_home()){\n //negate the ID of the 'feature' category e.g. '-6'\n $query-&gt;set('cat', '-6'); \n }\n}\nadd_action( 'pre_get_posts', 'hide_feature' );\n</code></pre>\n" }, { "answer_id": 393338, "author": "Jörn Schellhaas", "author_id": 142943, "author_profile": "https://wordpress.stackexchange.com/users/142943", "pm_score": 0, "selected": false, "text": "<p>Simplified version of the <a href=\"https://wordpress.stackexchange.com/a/230921/142943\">answer by Stefan Wimmer</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('get_the_terms', function ($terms, $post_id, $taxonomy) {\n // from https://wordpress.stackexchange.com/a/230921\n $exclude_categories = array(45);\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == &quot;category&quot; &amp;&amp; in_array($term-&gt;term_id, $exclude_categories)) {\n unset($terms[$key]);\n }\n }\n }\n return $terms;\n}, 100, 3);\n</code></pre>\n<p>I think that the call to <code>get_term_by</code> can be omitted and used <code>in_array</code> instead of a loop.</p>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181182", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24483/" ]
I have a category called `feature` which I use to have a feature post in the homepage. The problem is I don't want the category name `feature` to appear in this posts, but I want the other categories to show up. How could I do that?
To achieve this we need to use `get_the_category` [here](http://codex.wordpress.org/Function_Reference/get_the_category). I am going to use this code in several places, so it is more efficient to create a function ``` function exclude_cats($excludedcats = array()){ $categories = get_the_category(); $separator = ', '; $output = ''; foreach($categories as $category) { if ( !in_array($category->cat_ID, $excludedcats) ) { $output .= 'term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.''.$separator; } } echo trim($output, $separator); } ``` All that I've done inside the function was to call `get_the_category` function, But I've excluded the categories I don't want to show their names to not show. inside the index I've called the function like so `exclude_cats(array(11, 40, 53));`
181,185
<p>I am new to wordpress &amp; I am using a paid theme on my site <a href="http://www.freelancepulp.com" rel="nofollow">www.freelancepulp.com</a></p> <p>I want to know how I can identify if a plugin is good suit for my theme or not? I had to remove all the plugins on my site because it crashed the theme &amp; I was not able to go into Admin panel last night....</p> <p>Thank you for help!</p>
[ { "answer_id": 181186, "author": "Rahman Sharif", "author_id": 24483, "author_profile": "https://wordpress.stackexchange.com/users/24483", "pm_score": 3, "selected": true, "text": "<p>To achieve this we need to use <code>get_the_category</code> <a href=\"http://codex.wordpress.org/Function_Reference/get_the_category\" rel=\"nofollow\">here</a>.\nI am going to use this code in several places, so it is more efficient to create a function</p>\n\n<pre>\nfunction exclude_cats($excludedcats = array()){\n\n $categories = get_the_category();\n $separator = ', ';\n $output = '';\n foreach($categories as $category) {\n if ( !in_array($category->cat_ID, $excludedcats) ) {\n $output .= 'term_id ).'\" title=\"' . esc_attr( sprintf( __( \"View all posts in %s\" ), $category->name ) ) . '\">'.$category->cat_name.''.$separator;\n }\n }\n echo trim($output, $separator);\n\n}\n</pre>\n\n<p>All that I've done inside the function was to call <code>get_the_category</code> function, But I've excluded the categories I don't want to show their names to not show.</p>\n\n<p>inside the index I've called the function like so <code>exclude_cats(array(11, 40, 53));</code></p>\n" }, { "answer_id": 191837, "author": "Lafif Astahdziq", "author_id": 54707, "author_profile": "https://wordpress.stackexchange.com/users/54707", "pm_score": 0, "selected": false, "text": "<p>How about using <code>get_the_terms</code> filter like this,,</p>\n\n<pre><code>add_filter('get_the_terms', 'hide_categories_terms', 10, 3);\nfunction hide_categories_terms($terms, $post_id, $taxonomy){\n\n // get term to exclude by name, by id or maybe by slug\n $exclude = get_term_by('name', 'feature', 'category', ARRAY_A);\n\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == \"category\"){\n if(in_array($key, $exclude)) unset($terms[$key]);\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>i think it should works,,</p>\n" }, { "answer_id": 230921, "author": "Stefan Wimmer", "author_id": 97504, "author_profile": "https://wordpress.stackexchange.com/users/97504", "pm_score": 1, "selected": false, "text": "<p>I think @Lafif Astahdziq was on the right track - I like his approach even though it is fairly static. Here is how I rewrote it:</p>\n\n<pre><code>add_filter('get_the_terms', 'hide_categories_terms', 10, 3);\nfunction hide_categories_terms($terms, $post_id, $taxonomy){\n\n // define which category IDs you want to hide\n $excludeIDs = array(6);\n\n // get all the terms \n $exclude = array();\n foreach ($excludeIDs as $id) {\n $exclude[] = get_term_by('id', $id, 'category');\n }\n\n // filter the categories\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == \"category\"){\n foreach ($exclude as $exKey =&gt; $exTerm) {\n if($term-&gt;term_id == $exTerm-&gt;term_id) unset($terms[$key]);\n }\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>Put this in your functions.php and it will work.</p>\n" }, { "answer_id": 291167, "author": "Andy Gee", "author_id": 87583, "author_profile": "https://wordpress.stackexchange.com/users/87583", "pm_score": 0, "selected": false, "text": "<p>An old question but still quite popular so I have added another solution to add to your theme's functions.php file.</p>\n\n<pre><code>function hide_feature($query){\n if($query-&gt;is_main_query() &amp;&amp; $query-&gt;is_home()){\n //negate the ID of the 'feature' category e.g. '-6'\n $query-&gt;set('cat', '-6'); \n }\n}\nadd_action( 'pre_get_posts', 'hide_feature' );\n</code></pre>\n" }, { "answer_id": 393338, "author": "Jörn Schellhaas", "author_id": 142943, "author_profile": "https://wordpress.stackexchange.com/users/142943", "pm_score": 0, "selected": false, "text": "<p>Simplified version of the <a href=\"https://wordpress.stackexchange.com/a/230921/142943\">answer by Stefan Wimmer</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('get_the_terms', function ($terms, $post_id, $taxonomy) {\n // from https://wordpress.stackexchange.com/a/230921\n $exclude_categories = array(45);\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == &quot;category&quot; &amp;&amp; in_array($term-&gt;term_id, $exclude_categories)) {\n unset($terms[$key]);\n }\n }\n }\n return $terms;\n}, 100, 3);\n</code></pre>\n<p>I think that the call to <code>get_term_by</code> can be omitted and used <code>in_array</code> instead of a loop.</p>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181185", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69060/" ]
I am new to wordpress & I am using a paid theme on my site [www.freelancepulp.com](http://www.freelancepulp.com) I want to know how I can identify if a plugin is good suit for my theme or not? I had to remove all the plugins on my site because it crashed the theme & I was not able to go into Admin panel last night.... Thank you for help!
To achieve this we need to use `get_the_category` [here](http://codex.wordpress.org/Function_Reference/get_the_category). I am going to use this code in several places, so it is more efficient to create a function ``` function exclude_cats($excludedcats = array()){ $categories = get_the_category(); $separator = ', '; $output = ''; foreach($categories as $category) { if ( !in_array($category->cat_ID, $excludedcats) ) { $output .= 'term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.''.$separator; } } echo trim($output, $separator); } ``` All that I've done inside the function was to call `get_the_category` function, But I've excluded the categories I don't want to show their names to not show. inside the index I've called the function like so `exclude_cats(array(11, 40, 53));`
181,203
<p>I'm making shortcode and I'm stuck here. Here is code:</p> <pre><code>add_shortcode('service-shortcode', 'service_shortcode'); function service_shortcode($atts) { extract( shortcode_atts( array( 'title' =&gt; 'Service One', 'icon' =&gt; 'fa-briefcase' ), $atts )); $return_string = ''; $return_string .= '&lt;div class="service"&gt;'; $return_string .= '&lt;div class="container"&gt;'; $return_string .= '&lt;div class="row"&gt;'; $return_string .= '&lt;div class="col-md-3 col-sm-6"&gt;'; $return_string .= '&lt;div class="service-icon wow animated fadeInDown" data-wow-delay="300ms"&gt;'; $return_string .= '&lt;i class="fa '.$icon.'"&gt;&lt;/i&gt;'; $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;div class="text wow animated fadeInUp" data-wow-delay="300ms"&gt;'; $return_string .= '&lt;p&gt;'.$title.'&lt;/p&gt;'; $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; $return_string .= '&lt;/div&gt;'; return $return_string; } </code></pre> <p>Now when ever I put the shortcode it outputs the complete shortcode. What I want is for the first time it outputs complete shortcode and then just output from (div class="col-md-3 col-sm-6") to its closing tag. So the all services will come in a row.. Is there any way to achieve it. Thanks in advance..</p> <p>Note: I don't want to make custom post type that store each service and call with wp_query ... </p>
[ { "answer_id": 181186, "author": "Rahman Sharif", "author_id": 24483, "author_profile": "https://wordpress.stackexchange.com/users/24483", "pm_score": 3, "selected": true, "text": "<p>To achieve this we need to use <code>get_the_category</code> <a href=\"http://codex.wordpress.org/Function_Reference/get_the_category\" rel=\"nofollow\">here</a>.\nI am going to use this code in several places, so it is more efficient to create a function</p>\n\n<pre>\nfunction exclude_cats($excludedcats = array()){\n\n $categories = get_the_category();\n $separator = ', ';\n $output = '';\n foreach($categories as $category) {\n if ( !in_array($category->cat_ID, $excludedcats) ) {\n $output .= 'term_id ).'\" title=\"' . esc_attr( sprintf( __( \"View all posts in %s\" ), $category->name ) ) . '\">'.$category->cat_name.''.$separator;\n }\n }\n echo trim($output, $separator);\n\n}\n</pre>\n\n<p>All that I've done inside the function was to call <code>get_the_category</code> function, But I've excluded the categories I don't want to show their names to not show.</p>\n\n<p>inside the index I've called the function like so <code>exclude_cats(array(11, 40, 53));</code></p>\n" }, { "answer_id": 191837, "author": "Lafif Astahdziq", "author_id": 54707, "author_profile": "https://wordpress.stackexchange.com/users/54707", "pm_score": 0, "selected": false, "text": "<p>How about using <code>get_the_terms</code> filter like this,,</p>\n\n<pre><code>add_filter('get_the_terms', 'hide_categories_terms', 10, 3);\nfunction hide_categories_terms($terms, $post_id, $taxonomy){\n\n // get term to exclude by name, by id or maybe by slug\n $exclude = get_term_by('name', 'feature', 'category', ARRAY_A);\n\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == \"category\"){\n if(in_array($key, $exclude)) unset($terms[$key]);\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>i think it should works,,</p>\n" }, { "answer_id": 230921, "author": "Stefan Wimmer", "author_id": 97504, "author_profile": "https://wordpress.stackexchange.com/users/97504", "pm_score": 1, "selected": false, "text": "<p>I think @Lafif Astahdziq was on the right track - I like his approach even though it is fairly static. Here is how I rewrote it:</p>\n\n<pre><code>add_filter('get_the_terms', 'hide_categories_terms', 10, 3);\nfunction hide_categories_terms($terms, $post_id, $taxonomy){\n\n // define which category IDs you want to hide\n $excludeIDs = array(6);\n\n // get all the terms \n $exclude = array();\n foreach ($excludeIDs as $id) {\n $exclude[] = get_term_by('id', $id, 'category');\n }\n\n // filter the categories\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == \"category\"){\n foreach ($exclude as $exKey =&gt; $exTerm) {\n if($term-&gt;term_id == $exTerm-&gt;term_id) unset($terms[$key]);\n }\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>Put this in your functions.php and it will work.</p>\n" }, { "answer_id": 291167, "author": "Andy Gee", "author_id": 87583, "author_profile": "https://wordpress.stackexchange.com/users/87583", "pm_score": 0, "selected": false, "text": "<p>An old question but still quite popular so I have added another solution to add to your theme's functions.php file.</p>\n\n<pre><code>function hide_feature($query){\n if($query-&gt;is_main_query() &amp;&amp; $query-&gt;is_home()){\n //negate the ID of the 'feature' category e.g. '-6'\n $query-&gt;set('cat', '-6'); \n }\n}\nadd_action( 'pre_get_posts', 'hide_feature' );\n</code></pre>\n" }, { "answer_id": 393338, "author": "Jörn Schellhaas", "author_id": 142943, "author_profile": "https://wordpress.stackexchange.com/users/142943", "pm_score": 0, "selected": false, "text": "<p>Simplified version of the <a href=\"https://wordpress.stackexchange.com/a/230921/142943\">answer by Stefan Wimmer</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('get_the_terms', function ($terms, $post_id, $taxonomy) {\n // from https://wordpress.stackexchange.com/a/230921\n $exclude_categories = array(45);\n if (!is_admin()) {\n foreach($terms as $key =&gt; $term){\n if($term-&gt;taxonomy == &quot;category&quot; &amp;&amp; in_array($term-&gt;term_id, $exclude_categories)) {\n unset($terms[$key]);\n }\n }\n }\n return $terms;\n}, 100, 3);\n</code></pre>\n<p>I think that the call to <code>get_term_by</code> can be omitted and used <code>in_array</code> instead of a loop.</p>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68179/" ]
I'm making shortcode and I'm stuck here. Here is code: ``` add_shortcode('service-shortcode', 'service_shortcode'); function service_shortcode($atts) { extract( shortcode_atts( array( 'title' => 'Service One', 'icon' => 'fa-briefcase' ), $atts )); $return_string = ''; $return_string .= '<div class="service">'; $return_string .= '<div class="container">'; $return_string .= '<div class="row">'; $return_string .= '<div class="col-md-3 col-sm-6">'; $return_string .= '<div class="service-icon wow animated fadeInDown" data-wow-delay="300ms">'; $return_string .= '<i class="fa '.$icon.'"></i>'; $return_string .= '</div>'; $return_string .= '<div class="text wow animated fadeInUp" data-wow-delay="300ms">'; $return_string .= '<p>'.$title.'</p>'; $return_string .= '</div>'; $return_string .= '</div>'; $return_string .= '</div>'; $return_string .= '</div>'; $return_string .= '</div>'; return $return_string; } ``` Now when ever I put the shortcode it outputs the complete shortcode. What I want is for the first time it outputs complete shortcode and then just output from (div class="col-md-3 col-sm-6") to its closing tag. So the all services will come in a row.. Is there any way to achieve it. Thanks in advance.. Note: I don't want to make custom post type that store each service and call with wp\_query ...
To achieve this we need to use `get_the_category` [here](http://codex.wordpress.org/Function_Reference/get_the_category). I am going to use this code in several places, so it is more efficient to create a function ``` function exclude_cats($excludedcats = array()){ $categories = get_the_category(); $separator = ', '; $output = ''; foreach($categories as $category) { if ( !in_array($category->cat_ID, $excludedcats) ) { $output .= 'term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.''.$separator; } } echo trim($output, $separator); } ``` All that I've done inside the function was to call `get_the_category` function, But I've excluded the categories I don't want to show their names to not show. inside the index I've called the function like so `exclude_cats(array(11, 40, 53));`
181,219
<p>I'm trying to understand the difference between <a href="http://codex.wordpress.org/Function_Reference/get_site_option">get_site_option()</a> and <a href="http://codex.wordpress.org/Function_Reference/get_blog_option">get_blog_option()</a>.</p> <p>Are <em>blog</em> and <em>site</em> two different things? Apologies if this question seems basic, but when referring to a WordPress website, I've always used both terms very loosely (to mean the same thing). I'm now wondering if there is a difference?</p>
[ { "answer_id": 181229, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 3, "selected": false, "text": "<p><code>get_site_option()</code> - Gets a network wide option. This option is usually added in the Network Admin Settings section of a multisite set-up. If I had 50 sites, it would be a pain to go to 50 different sites and set the same option value. Instead I could set the option value once and have it apply across the network for all sites. See <a href=\"http://codex.wordpress.org/Function_Reference/get_site_option\">http://codex.wordpress.org/Function_Reference/get_site_option</a></p>\n\n<p><code>get_blog_option()</code> - Lets you get the value of an option for a specific site. One example might be to get the value of a user specific option for each site. So I could get all of the sites that the user belongs too, loop over the list of site IDs, and use <code>get_blog_option()</code> passing the <code>blog_id</code> and option name and get back the result. It's a convenience function that pretty much does the following:</p>\n\n<p><code>switch_to_blog( $id );\n$value = get_option( $option_name );\nrestore_current_blog();</code> </p>\n\n<p>See <a href=\"http://codex.wordpress.org/Function_Reference/get_blog_option\">http://codex.wordpress.org/Function_Reference/get_blog_option</a></p>\n\n<p><strong>tl;dr:</strong> <code>get_site_option()</code> gets a network wide value, <code>get_blog_option()</code> gets a specific value for a given site without needing to switch to that site first on your own. </p>\n" }, { "answer_id": 181231, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 5, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_option/\"><strong><code>get_option()</code></strong></a> returns an option for the <em>current</em> blog.</p>\n\n<p>In single site installation, the current blog is the only blog. So get <code>get_option()</code> returns the option for it.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_site_option/\"><strong><code>get_site_option()</code></strong></a> is used to retrieve an option network-wide. It means that you can get the same option from any site of the network.</p>\n\n<p>When this function is used in single installation, it <em>normally</em> returns the same thing of <code>get_option()</code>. The value may change because <code>get_site_option()</code> trigger filter hooks that are not triggered by <code>get_option()</code>.</p>\n\n<p>Note that once the <code>$wpdb-&gt;options</code> table is blog-specific, network-wide options are stored in the <a href=\"http://codex.wordpress.org/Database_Description#Table:_wp_sitemeta\"><code>$wpdb-&gt;sitemeta</code></a> table, that is specific of multisite installations.</p>\n\n<hr>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_blog_option/\"><strong><code>get_blog_option()</code></strong></a> is the only among the three functions that doesn't receive the option name as 1st argument, but its 1st argument is <code>$blog_id</code>.</p>\n\n<p>In fact, it is used in multisite installations to retrieve an option from a specific blog whose the id is known.</p>\n\n<p>What this function does is:</p>\n\n<pre><code>switch_to_blog( $blog_id );\n$value = get_option( $option, $default );\nrestore_current_blog();\n\nreturn $value;\n</code></pre>\n\n<p>If <code>$blog_id</code> is the same of current blog id, WordPress just skips the <code>switch_to_blog</code> part and just calls <code>get_option()</code>.</p>\n\n<p>This function is defined in the file <a href=\"https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/ms-blogs.php\"><code>wp-includes/ms-blogs.php</code></a> that is loaded only for multisite installation, so <code>get_blog_option()</code> is not defined in single site installations.</p>\n" }, { "answer_id": 378649, "author": "Dale Clifford", "author_id": 96739, "author_profile": "https://wordpress.stackexchange.com/users/96739", "pm_score": 1, "selected": false, "text": "<p>Although <code>get_option()</code> may retrieve the blog option on network sites, sometimes the network filters override the site option.</p>\n<p>For example: <code>users_can_register</code> for the site will always be overridden by the network setting.</p>\n<p>To retrieve the site option, sometimes you'll need to remove any network filters which are located in the ms-default-filters.php file in the WP Core.</p>\n<pre><code>remove_filter( 'option_users_can_register', 'users_can_register_signup_filter' ); // ignore network override\n$registration = get_option( 'users_can_register');\n</code></pre>\n" } ]
2015/03/14
[ "https://wordpress.stackexchange.com/questions/181219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
I'm trying to understand the difference between [get\_site\_option()](http://codex.wordpress.org/Function_Reference/get_site_option) and [get\_blog\_option()](http://codex.wordpress.org/Function_Reference/get_blog_option). Are *blog* and *site* two different things? Apologies if this question seems basic, but when referring to a WordPress website, I've always used both terms very loosely (to mean the same thing). I'm now wondering if there is a difference?
[**`get_option()`**](https://developer.wordpress.org/reference/functions/get_option/) returns an option for the *current* blog. In single site installation, the current blog is the only blog. So get `get_option()` returns the option for it. --- [**`get_site_option()`**](https://developer.wordpress.org/reference/functions/get_site_option/) is used to retrieve an option network-wide. It means that you can get the same option from any site of the network. When this function is used in single installation, it *normally* returns the same thing of `get_option()`. The value may change because `get_site_option()` trigger filter hooks that are not triggered by `get_option()`. Note that once the `$wpdb->options` table is blog-specific, network-wide options are stored in the [`$wpdb->sitemeta`](http://codex.wordpress.org/Database_Description#Table:_wp_sitemeta) table, that is specific of multisite installations. --- [**`get_blog_option()`**](https://developer.wordpress.org/reference/functions/get_blog_option/) is the only among the three functions that doesn't receive the option name as 1st argument, but its 1st argument is `$blog_id`. In fact, it is used in multisite installations to retrieve an option from a specific blog whose the id is known. What this function does is: ``` switch_to_blog( $blog_id ); $value = get_option( $option, $default ); restore_current_blog(); return $value; ``` If `$blog_id` is the same of current blog id, WordPress just skips the `switch_to_blog` part and just calls `get_option()`. This function is defined in the file [`wp-includes/ms-blogs.php`](https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/ms-blogs.php) that is loaded only for multisite installation, so `get_blog_option()` is not defined in single site installations.
181,256
<p>I have a basic custom query in WordPRess that loads all the users as shown in the following.</p> <p><code>SELECT DISTINCT users.* FROM " . $wpdb->users . " as users</code></p> <p>How do I modify it so that I can load users separately from each blog in multisite network? </p> <p>Please let me know</p> <p>Thanks</p>
[ { "answer_id": 181491, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Let me repeat what the comments are urging: Find a way to do this with the built in objects in WordPress.</p>\n\n<p>However, assuming you really, truly can't use a standard user query, and must use your custom query, you can at least leverage other, built-in WordPress functions to find the blogs to which each user has been assigned a permission.</p>\n\n<p>It's ugly to do so. It's complicated to do so. But it can be done.</p>\n\n<p><strong>Note</strong> I have not tested this code because I do not have WP set up for multiuser, but it should work, unless your install is considered a large network by <code>wp_is_large_network</code>.</p>\n\n<pre><code>//not sure how you are getting these user rows; I would do it this way, getting a results set for iteration\nglobal $wpdb;\n$users_rs = $wpdb-&gt;get_results( $wpdb-&gt;prepare( \"SELECT DISTINCT users FROM \" . $wpdb-&gt;users . \" AS users\" ) );\n\n//step 1: We need a list of all sites in this WPMU install\n$sites = wp_get_sites();\n\n/* step 2: we need to create an array to hold the users of each blog\n* outermost array: site IDs; middle array: blog IDs; inner array: users for each blog\n* technically we don't need to declare as an array but this makes it self-documenting in later code\n* ideally we would make this an object but let's not get carried away */\n$user_list_by_blog = array( array( array() ) );\n\n/* step 3: add blogs to $user_list_by_blog\n* first, we need to know which site we are currently on\n* so we start with a dummy value for a iteration variable \n* in theory wp_get_sites will be ordered by sites, then blogs\n* at least, we hope it's that way or this code won't work */\n$current_site = -1;\n\n//ok, now we can walk the sites and add the blogs for each site to our master list\nforeach( $sites as $site ) {\n if( $current_site != $site[ 'site_id' ] ) {\n $current_site = $site[ 'site_id' ] );\n }\n $user_list_by_blog[ $current_site ][] = $site[ 'blog_id' ];\n}\n\n/* step 4: we're ready to add users to the master list created above\n* now we walk the results set from the custom query\n* this thing is a bear, but it's as efficient as I can think to make it. */\nforeach( $users_rs as $user ) {\n //get the sites and blogs to which the user with that ID has access\n $user_blogs = get_blogs_of_user( $user-&gt;ID );\n\n //walk that result\n foreach( $user_blogs as $user_blog ) {\n for( $i = 0; $i &lt; count( $user_list_by_blog ); $i++ ) {\n if( $user_list_by_blog[ $i ] == $user_blog-&gt;site_id ) {\n //we have the right site, now let's find the right blog\n for( $x = 0; $x &lt; count( $user_list_by_blog[ $i ] ); $x++ ) {\n if( $user_list_by_blog[ $i ][ $x ] == $user_blog-&gt;blog_id ) {\n //we have the right blog, add the user id\n $user_list_by_blog[ $i ][ $x ][] = $user-&gt;ID;\n }\n }\n }\n }\n }\n}\n\n/* we now have, in $user_list_by_blog, a list of users by site and by blog\n* this is a record dump to show you the structure\n* wrap it in &lt;pre&gt; tags to make it pretty, if you like */\nvar_dump( $user_list_by_blog );\n</code></pre>\n\n<p>Did I mention what a terrible way of going about your desired end this code proves? Well, in case I didn't: <em>This is a terrible way of going about things.</em> Try to find a way to do what you want with WordPress' built-in functions. Really. Seriously. Try. Then try harder. Then try even harder. Because this isn't a good idea, this code I just wrote.</p>\n" }, { "answer_id": 181573, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>In following to my comments on the question the follow examples for a solution.</p>\n\n<h2>Default Function</h2>\n\n<p>WordPress have the function <code>get_users</code> to get all users for each site, works on single or multisite area. But to get all users from each site in Multisite network is the switch to each site important. The follow example demonstrate this.</p>\n\n<pre><code>// Multisite\n// get sites in the Multisite network\n$sites = wp_get_sites();\n// Switch in each Site\nforeach( $sites as $site ) {\n switch_to_blog( $site[ 'blog_id' ] );\n // Get Users of each site\n var_dump( count( get_users() ) );\n restore_current_blog();\n}\n</code></pre>\n\n<p>The code above get count (<code>count()</code>) all users in each site of the network.</p>\n\n<p>If you are in a single site of the network, then is the function <code>get_users()</code> enough to get all users of this site. The function use the WordPress global <code>$GLOBALS['blog_id']</code> to identifier the site on his ID. </p>\n\n<h2>Alternative for custom requirements</h2>\n\n<p>If the function is not helpful, use the <code>WP_User_Query</code> for your requirements.\nThe class give you a lot of possibilities to get user data in each site. Also use the helping hands of <code>switch_to_blog()</code> to switch on each site of the Multisite.\nSee the <a href=\"http://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\">codex</a> for helpful hints, parameters and example source.</p>\n\n<p>Small hint, the function <code>get_users</code> is a wrapper to use it easy of the <code>WP_User_Query</code>-class.</p>\n\n<h2>Hints for Multisite</h2>\n\n<h3>Grabbing Data From Another Blog in a Network</h3>\n\n<p>Getting data from another blog on the same multisite install can be done. Some people use SQL commands to do this, but this can be slow, and error prone.</p>\n\n<p>Although it's an inherently expensive operation, you can make use of switch_to_blog and <code>restore_current_blog</code> to make it easier, while using the standard WordPress APIs.</p>\n\n<pre><code>switch_to_blog( $blog_id );\n// Do something\nrestore_current_blog();\n</code></pre>\n\n<p><code>restore_current_blog</code> undos the last call to <code>switch_to_blog</code>, but only by one step, the calls are not nestable, so always call <code>restore_current_blog</code> before calling <code>switch_to_blog</code> again.</p>\n\n<h3>Large Network</h3>\n\n<p>Listing blogs in a network is possible, but it's an expensive thing to do.\nOn default is the WordPress count on 10.000 sites for a network. If you will change this value, see the source below.</p>\n\n<pre><code>add_filter( 'wp_is_large_network', function( $is_large, $type, $count ) {\n\n if ( ! $is_large )\n return $is_large;\n\n // $type can be 'sites' or 'users'\n if ( 'sites' !== $type )\n return $is_large;\n\n // Default is 10000, we add one 0\n return $count &gt; 100000;\n}, 10, 3 );\n</code></pre>\n\n<p>It can be done using the <code>wp_get_sites( $args )</code> function, available since version 3.7 of WordPress. The function accepts an array of arguments specifying the kind of sites you are looking for.</p>\n\n<p>The limit of this function is on 100 sites. If you network is bigger, then you must change this value via parameters on the function.</p>\n\n<h3>Cache</h3>\n\n<p>The function <code>wp_get_sites( $args )</code> is since 3.7 inside the core, but haven't a cache. If you use this often, transform the result in a cache, like <code>WP_Cache</code> or Transients.</p>\n\n<p>It is also a good idea to cache the <code>get_users()</code> result, much faster.</p>\n" } ]
2015/03/15
[ "https://wordpress.stackexchange.com/questions/181256", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48874/" ]
I have a basic custom query in WordPRess that loads all the users as shown in the following. `SELECT DISTINCT users.* FROM " . $wpdb->users . " as users` How do I modify it so that I can load users separately from each blog in multisite network? Please let me know Thanks
In following to my comments on the question the follow examples for a solution. Default Function ---------------- WordPress have the function `get_users` to get all users for each site, works on single or multisite area. But to get all users from each site in Multisite network is the switch to each site important. The follow example demonstrate this. ``` // Multisite // get sites in the Multisite network $sites = wp_get_sites(); // Switch in each Site foreach( $sites as $site ) { switch_to_blog( $site[ 'blog_id' ] ); // Get Users of each site var_dump( count( get_users() ) ); restore_current_blog(); } ``` The code above get count (`count()`) all users in each site of the network. If you are in a single site of the network, then is the function `get_users()` enough to get all users of this site. The function use the WordPress global `$GLOBALS['blog_id']` to identifier the site on his ID. Alternative for custom requirements ----------------------------------- If the function is not helpful, use the `WP_User_Query` for your requirements. The class give you a lot of possibilities to get user data in each site. Also use the helping hands of `switch_to_blog()` to switch on each site of the Multisite. See the [codex](http://codex.wordpress.org/Class_Reference/WP_User_Query) for helpful hints, parameters and example source. Small hint, the function `get_users` is a wrapper to use it easy of the `WP_User_Query`-class. Hints for Multisite ------------------- ### Grabbing Data From Another Blog in a Network Getting data from another blog on the same multisite install can be done. Some people use SQL commands to do this, but this can be slow, and error prone. Although it's an inherently expensive operation, you can make use of switch\_to\_blog and `restore_current_blog` to make it easier, while using the standard WordPress APIs. ``` switch_to_blog( $blog_id ); // Do something restore_current_blog(); ``` `restore_current_blog` undos the last call to `switch_to_blog`, but only by one step, the calls are not nestable, so always call `restore_current_blog` before calling `switch_to_blog` again. ### Large Network Listing blogs in a network is possible, but it's an expensive thing to do. On default is the WordPress count on 10.000 sites for a network. If you will change this value, see the source below. ``` add_filter( 'wp_is_large_network', function( $is_large, $type, $count ) { if ( ! $is_large ) return $is_large; // $type can be 'sites' or 'users' if ( 'sites' !== $type ) return $is_large; // Default is 10000, we add one 0 return $count > 100000; }, 10, 3 ); ``` It can be done using the `wp_get_sites( $args )` function, available since version 3.7 of WordPress. The function accepts an array of arguments specifying the kind of sites you are looking for. The limit of this function is on 100 sites. If you network is bigger, then you must change this value via parameters on the function. ### Cache The function `wp_get_sites( $args )` is since 3.7 inside the core, but haven't a cache. If you use this often, transform the result in a cache, like `WP_Cache` or Transients. It is also a good idea to cache the `get_users()` result, much faster.
181,275
<p>Consider this scenario: </p> <p>I enqueued some scripts in my custom theme. Then I set off to building a plugin that I want to be used only with that one theme. I want to enqueue other scripts in my plugin that depend on scripts enqueued in the theme. The standard way of declaring script dependencies in wordpress is passing an array of dependencies to <code>wp_enqueue_script</code>. E.g.:</p> <p><code>wp_enqueue_script('tagsinput-scripts', plugin_dir_url( __FILE__ ) . 'js/tagsinput/bootstrap-tagsinput.min.js', array('bootstrap-js'), '130215', false);</code></p> <p>would not be enqueued until <code>bootstrap-js</code> is enqueued.</p> <p>Imagine that the script above was enqueued by my plugin with <code>admin_enqueue_scripts</code> action hook, while <code>bootstrap-js</code> was enqueued in the theme with the <code>wp_enqueue_scripts</code> action hook.</p> <p>Can the dependency between <code>tagsinput-scripts</code> and <code>bootstrap-js</code> be properly resolved by Wordpress in this scenario when the two scripts where enqueued using different action hooks?</p>
[ { "answer_id": 181284, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>The simple answer is, \"No\". Although <code>admin_enqueue_scripts</code> and <code>wp_enqueue_scripts</code> hooks does exactly the same thing, the do their work in separate places which do not have any reference to the other.</p>\n\n<ul>\n<li><p><code>wp_enqueue_scripts</code> runs on the public side or front end </p></li>\n<li><p><code>admin_enqueue_scripts</code> As the name suggests, it runs on the admin side or back end</p></li>\n</ul>\n\n<p>Your script that with the dependency will thus never load if it is depended on a script that is loaded via the other hook.</p>\n\n<p>You will have to hook your <code>bootstrap-js</code> to both hooks for this to work, this will ensure that your dependency will work as well</p>\n\n<p>Example:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'enqueue_bootstrap_js' );\nadd_action( 'admin_enqueue_scripts', 'enqueue_bootstrap_js' );\n\nfunction enqueue_bootstrap_js()\n{\n //Register and enqueue your bootstrap-js script\n}\n\nadd_action( 'wp_enqueue_scripts', 'tagsinput_scripts' );\n\nfunction tagsinput_scripts()\n{\n wp_enqueue_script('tagsinput-scripts', plugin_dir_url( __FILE__ ) . 'js/tagsinput/bootstrap-tagsinput.min.js', array('bootstrap-js'), '130215', false);\n}\n</code></pre>\n" }, { "answer_id": 290129, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 2, "selected": false, "text": "<p>The simple answer is \"Yes\".</p>\n\n<p>Using <code>wp_enqueue_scripts</code> or <code>admin_enqueue_scripts</code> does make the script a dependency however it will only be recallable in the local environment. Thus only in the theme or plugin where you are registering it. However what what Pieter Goosen nor WordPress doesn't tell you is that you can use the <code>wp_default_scripts</code> hook to register an installation wide script.</p>\n\n<p><strong>How to use?</strong> See the note below, what's currently awaiting moderation for the \"User Contributed Notes\" of the <a href=\"https://developer.wordpress.org/reference/hooks/wp_default_scripts\" rel=\"nofollow noreferrer\"><code>wp_default_scripts</code> action hook at the WordPress Developer Resources</a>.</p>\n\n<hr>\n\n<p>Add a script where you can refer to from anywhere in your WordPress installation using <code>wp_enqueue_script</code> or <code>admin_enqueue_script</code>.</p>\n\n<p>First setup the hook, for example in your plugin.</p>\n\n<pre><code>add_action('wp_default_scripts', function(&amp;$scripts) {\n // Arguments order: `$scripts-&gt;add( 'handle', 'url', 'dependencies', 'version', 'in_footer' );`\n // Set \"in_footer\" argument to 1 to output the script in the footer.\n $scripts-&gt;add('my-plugin-script', '/path/to/my-plugin-script.js', array('jquery'), 'alpha', 1);\n});\n</code></pre>\n\n<p>Now you can use the script from the plugin anywhere for example in your theme.</p>\n\n<pre><code>add_action('wp_enqueue_scripts', function () {\n // Note the third argument: `array('my-plugin-script')`\n wp_enqueue_script('my-theme-script', '/path/to/my-theme-script.js', array('my-plugin-script'), null, true);\n});\n</code></pre>\n\n<p>Please make sure that you pick an identical string for the \"handle\" argument, a good practice is prefixing the handle name with your plugin or theme name.</p>\n" } ]
2015/03/15
[ "https://wordpress.stackexchange.com/questions/181275", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60985/" ]
Consider this scenario: I enqueued some scripts in my custom theme. Then I set off to building a plugin that I want to be used only with that one theme. I want to enqueue other scripts in my plugin that depend on scripts enqueued in the theme. The standard way of declaring script dependencies in wordpress is passing an array of dependencies to `wp_enqueue_script`. E.g.: `wp_enqueue_script('tagsinput-scripts', plugin_dir_url( __FILE__ ) . 'js/tagsinput/bootstrap-tagsinput.min.js', array('bootstrap-js'), '130215', false);` would not be enqueued until `bootstrap-js` is enqueued. Imagine that the script above was enqueued by my plugin with `admin_enqueue_scripts` action hook, while `bootstrap-js` was enqueued in the theme with the `wp_enqueue_scripts` action hook. Can the dependency between `tagsinput-scripts` and `bootstrap-js` be properly resolved by Wordpress in this scenario when the two scripts where enqueued using different action hooks?
The simple answer is, "No". Although `admin_enqueue_scripts` and `wp_enqueue_scripts` hooks does exactly the same thing, the do their work in separate places which do not have any reference to the other. * `wp_enqueue_scripts` runs on the public side or front end * `admin_enqueue_scripts` As the name suggests, it runs on the admin side or back end Your script that with the dependency will thus never load if it is depended on a script that is loaded via the other hook. You will have to hook your `bootstrap-js` to both hooks for this to work, this will ensure that your dependency will work as well Example: ``` add_action( 'wp_enqueue_scripts', 'enqueue_bootstrap_js' ); add_action( 'admin_enqueue_scripts', 'enqueue_bootstrap_js' ); function enqueue_bootstrap_js() { //Register and enqueue your bootstrap-js script } add_action( 'wp_enqueue_scripts', 'tagsinput_scripts' ); function tagsinput_scripts() { wp_enqueue_script('tagsinput-scripts', plugin_dir_url( __FILE__ ) . 'js/tagsinput/bootstrap-tagsinput.min.js', array('bootstrap-js'), '130215', false); } ```
181,291
<p>I have category_id=3 and have 10 post in category_id=3 with post_id= 1=>10</p> <p>How to show list post category_id=3 with no post_id=1,3,5 value as </p> <pre><code>query_posts('cat=3&amp; -p=1,3,5 &amp;showposts=30 </code></pre>
[ { "answer_id": 181292, "author": "grandcoder", "author_id": 69121, "author_profile": "https://wordpress.stackexchange.com/users/69121", "pm_score": 2, "selected": true, "text": "<p>If you are trying to omit posts 1,3,5 from category 3 on your blog, you can use the following code</p>\n\n<pre><code>$query = new WP_Query( array('cat' =&gt; 3, 'post_type' =&gt; 'post', 'post__not_in' =&gt; array(1,3,5) ) );\n</code></pre>\n\n<p>The query results will not show posts with ids 1,3,5 of category 3.</p>\n" }, { "answer_id": 181316, "author": "Vee", "author_id": 44979, "author_profile": "https://wordpress.stackexchange.com/users/44979", "pm_score": -1, "selected": false, "text": "<p>You have placed minus sign before the parameter. This only work for inclusion of post. </p>\n\n<p>For exclusion you have to use like this </p>\n\n<pre><code>query_posts(array('posts_per_page' =&gt; 10, 'post__not_in' =&gt; array(1,3,5)));\n</code></pre>\n\n<p>Check this in Wordpress <a href=\"http://codex.wordpress.org/Function_Reference/query_posts#Passing_variables_to_query_posts\" rel=\"nofollow\">Codex</a></p>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65359/" ]
I have category\_id=3 and have 10 post in category\_id=3 with post\_id= 1=>10 How to show list post category\_id=3 with no post\_id=1,3,5 value as ``` query_posts('cat=3& -p=1,3,5 &showposts=30 ```
If you are trying to omit posts 1,3,5 from category 3 on your blog, you can use the following code ``` $query = new WP_Query( array('cat' => 3, 'post_type' => 'post', 'post__not_in' => array(1,3,5) ) ); ``` The query results will not show posts with ids 1,3,5 of category 3.
181,297
<p>So, where is the searchresult page sidebar located?</p> <p>For example, in the searchresult page, there is "A" sidebar.</p> <p>However, I want to change it to "B" sidebar.</p> <p>I looked at <code>search.php</code> but could not understand where the sidebar was coming from.</p>
[ { "answer_id": 181298, "author": "grandcoder", "author_id": 69121, "author_profile": "https://wordpress.stackexchange.com/users/69121", "pm_score": 1, "selected": true, "text": "<p>Your search.php may contain the following code</p>\n\n<pre><code>&lt;?php get_sidebar(); ?&gt;\n</code></pre>\n\n<p>If a name ($name) is specified as an argument then a specialized sidebar sidebar-{name}.php will be included. If sidebar-{name}.php does not exist, then it will fallback to loading sidebar.php.</p>\n\n<p>If the theme contains no sidebar.php file then the sidebar from the default theme will be included</p>\n" }, { "answer_id": 181314, "author": "Vee", "author_id": 44979, "author_profile": "https://wordpress.stackexchange.com/users/44979", "pm_score": -1, "selected": false, "text": "<p>You can create a new sidebar with name <code>sidebar-search.php</code> and call it on <code>search.php</code> page using </p>\n\n<pre><code>&lt;?php get_sidebar('search'); ?&gt;\n</code></pre>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So, where is the searchresult page sidebar located? For example, in the searchresult page, there is "A" sidebar. However, I want to change it to "B" sidebar. I looked at `search.php` but could not understand where the sidebar was coming from.
Your search.php may contain the following code ``` <?php get_sidebar(); ?> ``` If a name ($name) is specified as an argument then a specialized sidebar sidebar-{name}.php will be included. If sidebar-{name}.php does not exist, then it will fallback to loading sidebar.php. If the theme contains no sidebar.php file then the sidebar from the default theme will be included
181,301
<p>I am building a wordpress website with drop down menu (sub menu).</p> <p><img src="https://i.stack.imgur.com/4F667.png" alt="enter image description here"></p> <p>To achieve this here I am using wordpress <strong>walker</strong> class. This is the code which I am using in my <strong>functions.php</strong></p> <pre><code>class CSS_Menu_Maker_Walker extends Walker { var $db_fields = array( 'parent' =&gt; 'menu_item_parent', 'id' =&gt; 'db_id' ); function start_lvl( &amp;$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent&lt;ul&gt;\n"; } function end_lvl( &amp;$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent&lt;/ul&gt;\n"; } function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; /* Add active class */ if(in_array('current-menu-item', $classes)) { $classes[] = 'current'; unset($classes['current-menu-item']); } /* Check for children */ $children = get_posts(array('post_type' =&gt; 'nav_menu_item', 'nopaging' =&gt; true, 'numberposts' =&gt; 1, 'meta_key' =&gt; '_menu_item_menu_item_parent', 'meta_value' =&gt; $item-&gt;ID)); if (!empty($children)) { $classes[] = 'has-children'; } $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '&lt;li' . $id . $value . $class_names .'&gt;'; $attributes = ! empty( $item-&gt;attr_title ) ? ' title="' . esc_attr( $item-&gt;attr_title ) .'"' : ''; $attributes .= ! empty( $item-&gt;target ) ? ' target="' . esc_attr( $item-&gt;target ) .'"' : ''; $attributes .= ! empty( $item-&gt;xfn ) ? ' rel="' . esc_attr( $item-&gt;xfn ) .'"' : ''; $attributes .= ! empty( $item-&gt;url ) ? ' href="' . esc_attr( $item-&gt;url ) .'"' : ''; $item_output = $args-&gt;before; $item_output .= '&lt;a'. $attributes .'&gt;'; $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after; $item_output .= '&lt;/a&gt;'; $item_output .= $args-&gt;after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } function end_el( &amp;$output, $item, $depth = 0, $args = array() ) { $output .= "&lt;/li&gt;\n"; } } </code></pre> <p>To try demonstrating what I am trying to accomplish please look at the follwoing HTML:</p> <pre><code> &lt;nav id="nav-wrap"&gt; &lt;a class="mobile-btn" href="#nav-wrap" title="Show navigation"&gt;Show Menu&lt;/a&gt; &lt;a class="mobile-btn" href="#" title="Hide navigation"&gt;Hide Menu&lt;/a&gt; &lt;div class="row"&gt; &lt;ul id="nav" class="nav"&gt; &lt;li class="current"&gt;&lt;a href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="has-children"&gt;&lt;a href="#"&gt;Dropdown&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Submenu 01&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Submenu 02&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Submenu 03&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="demo.html"&gt;Demo&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="archives.html"&gt;Archives&lt;/a&gt;&lt;/li&gt; &lt;li class="has-children"&gt;&lt;a href="single.html"&gt;Blog&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="blog.html"&gt;Blog Entries&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="single.html"&gt;Single Blog&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="page.html"&gt;Page&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!-- end #nav --&gt; &lt;/div&gt; &lt;/nav&gt; &lt;!-- end #nav-wrap --&gt; </code></pre> <p>Explanation:</p> <ol> <li>There is a main nav tag with a class called: "<strong>nav-wrap</strong>"</li> <li>Inside just a simple div tag with a class called: "<strong>row</strong>"</li> <li>Inside just a simple (<strong>ul li a</strong>) where ul tag of a class and id "nav"</li> <li>Drop Down wrapped with a div with a class called: "<strong>has-children</strong>"</li> <li>When a user clicks on any item the class "current" is called</li> <li>The class "<strong>current</strong>" is not called when a user clicks on any sub item. In, this case class "current" is applied on its parent. for e.g here when a user clicks on "Blog Entries" then class "current" is applied on its parent i.e "Blog"</li> </ol> <p><img src="https://i.stack.imgur.com/R2Yb5.png" alt="enter image description here"></p> <p>But what I am actually getting is:</p> <pre><code>&lt;nav id="nav-wrap"&gt; &lt;a class="mobile-btn" href="#nav-wrap" title="Show navigation"&gt;Show Menu&lt;/a&gt; &lt;a class="mobile-btn" href="#" title="Hide navigation"&gt;Hide Menu&lt;/a&gt; &lt;div class="row"&gt;&lt;ul id="nav" class="nav"&gt;&lt;li id="menu-item-557" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home current"&gt;&lt;a href="http://127.0.0.1/wordpress/"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li id="menu-item-558" class="menu-item menu-item-type-post_type menu-item-object-page"&gt;&lt;a href="http://127.0.0.1/wordpress/about-us/"&gt;About Us&lt;/a&gt;&lt;/li&gt; &lt;li id="menu-item-559" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children has-children"&gt;&lt;a href="http://127.0.0.1/wordpress/blog/"&gt;Blog&lt;/a&gt; &lt;ul&gt; &lt;li id="menu-item-564" class="menu-item menu-item-type-taxonomy menu-item-object-category"&gt;&lt;a href="http://127.0.0.1/wordpress/blog/category/blogger/"&gt;Blogger&lt;/a&gt;&lt;/li&gt; &lt;li id="menu-item-565" class="menu-item menu-item-type-taxonomy menu-item-object-category"&gt;&lt;a href="http://127.0.0.1/wordpress/blog/category/html-css/"&gt;HTML-CSS&lt;/a&gt;&lt;/li&gt; &lt;li id="menu-item-566" class="menu-item menu-item-type-taxonomy menu-item-object-category"&gt;&lt;a href="http://127.0.0.1/wordpress/blog/category/psd/"&gt;PSD&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li id="menu-item-560" class="menu-item menu-item-type-post_type menu-item-object-page"&gt;&lt;a href="http://127.0.0.1/wordpress/contact-us/"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/div&gt; &lt;/nav&gt; &lt;!-- end #nav-wrap --&gt; </code></pre> <p>This is the code which I am using to output my menu in <strong>header.php</strong></p> <pre><code>&lt;nav id="nav-wrap"&gt; &lt;a class="mobile-btn" href="#nav-wrap" title="Show navigation"&gt;Show Menu&lt;/a&gt; &lt;a class="mobile-btn" href="#" title="Hide navigation"&gt;Hide Menu&lt;/a&gt; &lt;?php wp_nav_menu(array( 'menu' =&gt; 'Main Navigation', 'menu_class' =&gt; 'nav', 'menu_id' =&gt; 'nav', 'container_class' =&gt; 'row', 'walker' =&gt; new CSS_Menu_Maker_Walker() )); ?&gt; &lt;/nav&gt; &lt;!-- end #nav-wrap --&gt; </code></pre> <p><img src="https://i.stack.imgur.com/bXg7o.png" alt="enter image description here"></p> <p>But, the problem is it's also applying "current" class when I click on any sub-item which I don't want. So, what should I do to remove "current" class in a submenu item and apply that on its parent class. </p> <p>This is the <a href="http://www.styleshout.com/free-templates/keep-it-simple/" rel="nofollow noreferrer">template</a> which I am converting in wp.</p>
[ { "answer_id": 181305, "author": "ucon89", "author_id": 44538, "author_profile": "https://wordpress.stackexchange.com/users/44538", "pm_score": 0, "selected": false, "text": "<p>@raunak how about use jQuery <code>jQuery(\" ul li .menu-item\").removeClass( \"current\" );</code> for adding to parent <code>jQuery(\".current-menu-parent\").addClass( \"current\" );</code></p>\n" }, { "answer_id": 228813, "author": "webHasan", "author_id": 44137, "author_profile": "https://wordpress.stackexchange.com/users/44137", "pm_score": 2, "selected": true, "text": "<p>Use following code as jQuery:</p>\n\n<pre><code>jQuery('#nav li').removeClass('current');\njQuery('#nav&gt;li.current-menu-item').addClass('current');\njQuery('.has-children li.current-menu-item').closest('.has-children').addClass('current');\n</code></pre>\n\n<p>See jsfiddle (current item red color). When you click \"Single Blog\" menu item your html structure will like my following example and jQuery will remove class active from it and add class it's parent exactly like what you wanted. \n<a href=\"https://jsfiddle.net/dom8188s/\" rel=\"nofollow\">https://jsfiddle.net/dom8188s/</a></p>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62377/" ]
I am building a wordpress website with drop down menu (sub menu). ![enter image description here](https://i.stack.imgur.com/4F667.png) To achieve this here I am using wordpress **walker** class. This is the code which I am using in my **functions.php** ``` class CSS_Menu_Maker_Walker extends Walker { var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' ); function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul>\n"; } function end_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n"; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; /* Add active class */ if(in_array('current-menu-item', $classes)) { $classes[] = 'current'; unset($classes['current-menu-item']); } /* Check for children */ $children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID)); if (!empty($children)) { $classes[] = 'has-children'; } $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names .'>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } function end_el( &$output, $item, $depth = 0, $args = array() ) { $output .= "</li>\n"; } } ``` To try demonstrating what I am trying to accomplish please look at the follwoing HTML: ``` <nav id="nav-wrap"> <a class="mobile-btn" href="#nav-wrap" title="Show navigation">Show Menu</a> <a class="mobile-btn" href="#" title="Hide navigation">Hide Menu</a> <div class="row"> <ul id="nav" class="nav"> <li class="current"><a href="index.html">Home</a></li> <li class="has-children"><a href="#">Dropdown</a> <ul> <li><a href="#">Submenu 01</a></li> <li><a href="#">Submenu 02</a></li> <li><a href="#">Submenu 03</a></li> </ul> </li> <li><a href="demo.html">Demo</a></li> <li><a href="archives.html">Archives</a></li> <li class="has-children"><a href="single.html">Blog</a> <ul> <li><a href="blog.html">Blog Entries</a></li> <li><a href="single.html">Single Blog</a></li> </ul> </li> <li><a href="page.html">Page</a></li> </ul> <!-- end #nav --> </div> </nav> <!-- end #nav-wrap --> ``` Explanation: 1. There is a main nav tag with a class called: "**nav-wrap**" 2. Inside just a simple div tag with a class called: "**row**" 3. Inside just a simple (**ul li a**) where ul tag of a class and id "nav" 4. Drop Down wrapped with a div with a class called: "**has-children**" 5. When a user clicks on any item the class "current" is called 6. The class "**current**" is not called when a user clicks on any sub item. In, this case class "current" is applied on its parent. for e.g here when a user clicks on "Blog Entries" then class "current" is applied on its parent i.e "Blog" ![enter image description here](https://i.stack.imgur.com/R2Yb5.png) But what I am actually getting is: ``` <nav id="nav-wrap"> <a class="mobile-btn" href="#nav-wrap" title="Show navigation">Show Menu</a> <a class="mobile-btn" href="#" title="Hide navigation">Hide Menu</a> <div class="row"><ul id="nav" class="nav"><li id="menu-item-557" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home current"><a href="http://127.0.0.1/wordpress/">Home</a></li> <li id="menu-item-558" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="http://127.0.0.1/wordpress/about-us/">About Us</a></li> <li id="menu-item-559" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children has-children"><a href="http://127.0.0.1/wordpress/blog/">Blog</a> <ul> <li id="menu-item-564" class="menu-item menu-item-type-taxonomy menu-item-object-category"><a href="http://127.0.0.1/wordpress/blog/category/blogger/">Blogger</a></li> <li id="menu-item-565" class="menu-item menu-item-type-taxonomy menu-item-object-category"><a href="http://127.0.0.1/wordpress/blog/category/html-css/">HTML-CSS</a></li> <li id="menu-item-566" class="menu-item menu-item-type-taxonomy menu-item-object-category"><a href="http://127.0.0.1/wordpress/blog/category/psd/">PSD</a></li> </ul> </li> <li id="menu-item-560" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="http://127.0.0.1/wordpress/contact-us/">Contact</a></li> </ul></div> </nav> <!-- end #nav-wrap --> ``` This is the code which I am using to output my menu in **header.php** ``` <nav id="nav-wrap"> <a class="mobile-btn" href="#nav-wrap" title="Show navigation">Show Menu</a> <a class="mobile-btn" href="#" title="Hide navigation">Hide Menu</a> <?php wp_nav_menu(array( 'menu' => 'Main Navigation', 'menu_class' => 'nav', 'menu_id' => 'nav', 'container_class' => 'row', 'walker' => new CSS_Menu_Maker_Walker() )); ?> </nav> <!-- end #nav-wrap --> ``` ![enter image description here](https://i.stack.imgur.com/bXg7o.png) But, the problem is it's also applying "current" class when I click on any sub-item which I don't want. So, what should I do to remove "current" class in a submenu item and apply that on its parent class. This is the [template](http://www.styleshout.com/free-templates/keep-it-simple/) which I am converting in wp.
Use following code as jQuery: ``` jQuery('#nav li').removeClass('current'); jQuery('#nav>li.current-menu-item').addClass('current'); jQuery('.has-children li.current-menu-item').closest('.has-children').addClass('current'); ``` See jsfiddle (current item red color). When you click "Single Blog" menu item your html structure will like my following example and jQuery will remove class active from it and add class it's parent exactly like what you wanted. <https://jsfiddle.net/dom8188s/>
181,326
<p>Speaking about backoffice here.</p> <p>I usually add columns and filters to the backoffice for certain custom post types. No problem here. BUt what if I would simply like to change something on the content of the default columns? For example, how to change the color of the post titles? And say, only some titles on a list, for example based on the terms the post belongs to?</p> <p>I would just need an action like </p> <pre><code>manage_{$post-&gt;post_type}_posts_custom_column </code></pre> <p>But for regular/default columns. The above action only reach custom columns.</p>
[ { "answer_id": 181330, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>CSS is the answer. If you look at the HTML code of each row (<code>&lt;tr&gt;</code>), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags.</p>\n\n<p>For example, this is a row in one of my site:</p>\n\n<pre><code>&lt;tr id=\"post-24392\" class=\"post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0\"&gt;\n &lt;th scope=\"row\" class=\"check-column\"&gt;\n &lt;label class=\"screen-reader-text\" for=\"cb-select-24392\"&gt;Elige ¿?&lt;/label&gt;\n &lt;input id=\"cb-select-24392\" type=\"checkbox\" name=\"post[]\" value=\"24392\"&gt;\n &lt;div class=\"locked-indicator\"&gt;&lt;/div&gt;\n &lt;/th&gt;\n &lt;td class=\"post-title page-title column-title\"&gt;\n Here the title\n</code></pre>\n\n<p>If I want to change the color of the title if the post belongs to \"metro\" tag:</p>\n\n<pre><code>.tag-metro .post-title {\n color: red;\n}\n</code></pre>\n\n<p>You can put that CSS in a file and <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">enqueue it in admin</a>.</p>\n\n<p>If terms are from a custom taxonomy, you can hook post_class to add the classes based on the custom taxonomy:</p>\n\n<pre><code>add_filter( 'post_class', function( $classes, $class, $ID ) {\n\n $taxonomy = 'my-custom-taxonomy';\n\n $terms = get_the_terms( (int) $ID, $taxonomy );\n\n if( !empty( $terms ) ) {\n\n foreach( (array) $terms as $order =&gt; $term ) {\n\n if( !in_array( $term-&gt;slug, $classes ) ) {\n\n $classes[] = $term-&gt;slug;\n\n }\n\n }\n\n }\n\n return $classes;\n\n}, 10, 3 );\n</code></pre>\n" }, { "answer_id": 181334, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 0, "selected": false, "text": "<p>Unluckily does not exists a filter like that. However, output pass throught WordPress <em>usual</em> filters. E.g. <code>'the_title'</code> for title.</p>\n\n<p>The only problem is that you can't just add a filter to the <code>'the_title'</code>, because it will affect a lot of things. However you can use filters that are triggered only on post list admin screen (<code>edit.php</code>) to add the filter to title.</p>\n\n<p>As example:</p>\n\n<pre><code>// this filter is fired only on edit.php for 'post' post type\nadd_filter('manage_edit-post_sortable_columns', function($sortable) {\n\n // add a filter to post title. Use the lowest possible priority. \n add_filter('the_title', 'my_admin_title_color', PHP_INT_MAX);\n\n return $sortable;\n});\n\nfunction my_admin_title_color($title) {\n // you can use template tags or even access to global $post\n if ( has_category('uncategorized') ) {\n $title = '&lt;span style=\"color:#f00\"&gt;'.$title.'&lt;/span&gt;';\n }\n\n return $title;\n}\n</code></pre>\n\n<p>In code above I used <code>'manage_edit-post_sortable_columns'</code> because is a filter that is fired only on <code>edit.php</code> for 'post' post type.</p>\n\n<p>It is one of the <a href=\"https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/\" rel=\"nofollow\"><code>\"manage_{$screen_id}_sortable_columns\"</code></a>, filters that is triggered with a different name for different post types. As example you ca use <code>\"manage_edit-page_sortable_columns\"</code> to target pages. This <em>specificity</em> allow to add pretty safely the widely used <code>the_title</code> filter hook. Moreover by using a very low priority compatibility with other filters should be assured.</p>\n\n<p>After that you can just wrap the title with a span with some custom styles (as done in my example code), or some custom HTML class to be styles with external CSS.</p>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181326", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10381/" ]
Speaking about backoffice here. I usually add columns and filters to the backoffice for certain custom post types. No problem here. BUt what if I would simply like to change something on the content of the default columns? For example, how to change the color of the post titles? And say, only some titles on a list, for example based on the terms the post belongs to? I would just need an action like ``` manage_{$post->post_type}_posts_custom_column ``` But for regular/default columns. The above action only reach custom columns.
CSS is the answer. If you look at the HTML code of each row (`<tr>`), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags. For example, this is a row in one of my site: ``` <tr id="post-24392" class="post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0"> <th scope="row" class="check-column"> <label class="screen-reader-text" for="cb-select-24392">Elige ¿?</label> <input id="cb-select-24392" type="checkbox" name="post[]" value="24392"> <div class="locked-indicator"></div> </th> <td class="post-title page-title column-title"> Here the title ``` If I want to change the color of the title if the post belongs to "metro" tag: ``` .tag-metro .post-title { color: red; } ``` You can put that CSS in a file and [enqueue it in admin](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts). If terms are from a custom taxonomy, you can hook post\_class to add the classes based on the custom taxonomy: ``` add_filter( 'post_class', function( $classes, $class, $ID ) { $taxonomy = 'my-custom-taxonomy'; $terms = get_the_terms( (int) $ID, $taxonomy ); if( !empty( $terms ) ) { foreach( (array) $terms as $order => $term ) { if( !in_array( $term->slug, $classes ) ) { $classes[] = $term->slug; } } } return $classes; }, 10, 3 ); ```
181,342
<p>I'm renting a server from <a href="http://digitalocean.com/" rel="nofollow noreferrer">DigitalOcean</a> on which I'm running Wordpress inside apache on port 8079. DigitalOcean also only allows one to connect via SFTP. Currently the client I use to do that is <a href="http://panic.com/transmit/" rel="nofollow noreferrer">Transmit</a> . My details for that is like follow:</p> <p><img src="https://i.stack.imgur.com/LWe4N.png" alt="enter image description here"></p> <p>So since my apache instance is running on port 8079, does that mean that when Wordpress asks for my FTP details that it'll look something like this?:</p> <p><img src="https://i.stack.imgur.com/TxTzN.png" alt="enter image description here"></p> <p>Because it's not working. My Wordpress installation on my server is under <code>/var/www/previews/sample/</code></p>
[ { "answer_id": 181330, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>CSS is the answer. If you look at the HTML code of each row (<code>&lt;tr&gt;</code>), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags.</p>\n\n<p>For example, this is a row in one of my site:</p>\n\n<pre><code>&lt;tr id=\"post-24392\" class=\"post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0\"&gt;\n &lt;th scope=\"row\" class=\"check-column\"&gt;\n &lt;label class=\"screen-reader-text\" for=\"cb-select-24392\"&gt;Elige ¿?&lt;/label&gt;\n &lt;input id=\"cb-select-24392\" type=\"checkbox\" name=\"post[]\" value=\"24392\"&gt;\n &lt;div class=\"locked-indicator\"&gt;&lt;/div&gt;\n &lt;/th&gt;\n &lt;td class=\"post-title page-title column-title\"&gt;\n Here the title\n</code></pre>\n\n<p>If I want to change the color of the title if the post belongs to \"metro\" tag:</p>\n\n<pre><code>.tag-metro .post-title {\n color: red;\n}\n</code></pre>\n\n<p>You can put that CSS in a file and <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">enqueue it in admin</a>.</p>\n\n<p>If terms are from a custom taxonomy, you can hook post_class to add the classes based on the custom taxonomy:</p>\n\n<pre><code>add_filter( 'post_class', function( $classes, $class, $ID ) {\n\n $taxonomy = 'my-custom-taxonomy';\n\n $terms = get_the_terms( (int) $ID, $taxonomy );\n\n if( !empty( $terms ) ) {\n\n foreach( (array) $terms as $order =&gt; $term ) {\n\n if( !in_array( $term-&gt;slug, $classes ) ) {\n\n $classes[] = $term-&gt;slug;\n\n }\n\n }\n\n }\n\n return $classes;\n\n}, 10, 3 );\n</code></pre>\n" }, { "answer_id": 181334, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 0, "selected": false, "text": "<p>Unluckily does not exists a filter like that. However, output pass throught WordPress <em>usual</em> filters. E.g. <code>'the_title'</code> for title.</p>\n\n<p>The only problem is that you can't just add a filter to the <code>'the_title'</code>, because it will affect a lot of things. However you can use filters that are triggered only on post list admin screen (<code>edit.php</code>) to add the filter to title.</p>\n\n<p>As example:</p>\n\n<pre><code>// this filter is fired only on edit.php for 'post' post type\nadd_filter('manage_edit-post_sortable_columns', function($sortable) {\n\n // add a filter to post title. Use the lowest possible priority. \n add_filter('the_title', 'my_admin_title_color', PHP_INT_MAX);\n\n return $sortable;\n});\n\nfunction my_admin_title_color($title) {\n // you can use template tags or even access to global $post\n if ( has_category('uncategorized') ) {\n $title = '&lt;span style=\"color:#f00\"&gt;'.$title.'&lt;/span&gt;';\n }\n\n return $title;\n}\n</code></pre>\n\n<p>In code above I used <code>'manage_edit-post_sortable_columns'</code> because is a filter that is fired only on <code>edit.php</code> for 'post' post type.</p>\n\n<p>It is one of the <a href=\"https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/\" rel=\"nofollow\"><code>\"manage_{$screen_id}_sortable_columns\"</code></a>, filters that is triggered with a different name for different post types. As example you ca use <code>\"manage_edit-page_sortable_columns\"</code> to target pages. This <em>specificity</em> allow to add pretty safely the widely used <code>the_title</code> filter hook. Moreover by using a very low priority compatibility with other filters should be assured.</p>\n\n<p>After that you can just wrap the title with a span with some custom styles (as done in my example code), or some custom HTML class to be styles with external CSS.</p>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181342", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69150/" ]
I'm renting a server from [DigitalOcean](http://digitalocean.com/) on which I'm running Wordpress inside apache on port 8079. DigitalOcean also only allows one to connect via SFTP. Currently the client I use to do that is [Transmit](http://panic.com/transmit/) . My details for that is like follow: ![enter image description here](https://i.stack.imgur.com/LWe4N.png) So since my apache instance is running on port 8079, does that mean that when Wordpress asks for my FTP details that it'll look something like this?: ![enter image description here](https://i.stack.imgur.com/TxTzN.png) Because it's not working. My Wordpress installation on my server is under `/var/www/previews/sample/`
CSS is the answer. If you look at the HTML code of each row (`<tr>`), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags. For example, this is a row in one of my site: ``` <tr id="post-24392" class="post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0"> <th scope="row" class="check-column"> <label class="screen-reader-text" for="cb-select-24392">Elige ¿?</label> <input id="cb-select-24392" type="checkbox" name="post[]" value="24392"> <div class="locked-indicator"></div> </th> <td class="post-title page-title column-title"> Here the title ``` If I want to change the color of the title if the post belongs to "metro" tag: ``` .tag-metro .post-title { color: red; } ``` You can put that CSS in a file and [enqueue it in admin](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts). If terms are from a custom taxonomy, you can hook post\_class to add the classes based on the custom taxonomy: ``` add_filter( 'post_class', function( $classes, $class, $ID ) { $taxonomy = 'my-custom-taxonomy'; $terms = get_the_terms( (int) $ID, $taxonomy ); if( !empty( $terms ) ) { foreach( (array) $terms as $order => $term ) { if( !in_array( $term->slug, $classes ) ) { $classes[] = $term->slug; } } } return $classes; }, 10, 3 ); ```
181,354
<p>I am trying to use ajax in wordpress I have two comboboxes in single-meetings.php the second combobox values are based on selection from the first one</p> <p>here is my <code>single-meetings.php</code></p> <pre><code>&lt;form action="#" name="form" id="form" method="post"&gt; &lt;div id="check-in-date-wrap"&gt; &lt;select name="search_category" id="check-in-date"&gt; &lt;option value="03/10/2015"&gt;"03/10/2015"&lt;/option&gt; &lt;option value="03/11/2015"&gt;"03/11/2015"&lt;/option&gt; &lt;option value="03/12/2015"&gt;"03/12/2015"&lt;/option&gt; &lt;option value="03/13/2015"&gt;"03/13/2015"&lt;/option&gt; &lt;/select&gt; &lt;div id="check-out-date-wrap"&gt; // a combobox should be created here &lt;/div&gt; &lt;img src="loader.gif" style="margin-top:8px; float:left" id="loader" alt="" /&gt; &lt;input type="submit" name="" value="GO" /&gt; &lt;/form&gt; </code></pre> <p>I have two another files, php and js </p> <p>this is my php code <code>combo_check-out.php</code></p> <pre><code> &lt;?php function iRange($first, $last, $format = 'm/d/Y' ) { $dates = array(); $current = strtotime($first); $i=1; while( $i &lt;= $last ) { $dates[] = date($format, $current); $current = strtotime('+1 day', $current); $i++; } $time = date("m/d/Y",$current); return $time; } if($_REQUEST) { $id = $_REQUEST['parent_id']; ?&gt; &lt;select name="check-out" id="check-out-date"&gt; &lt;option value="&lt;?php echo iRange($id, 1, $format = 'm/d/Y' ) ?&gt;"&gt;"1 Day (Same Day)"&lt;/option&gt; &lt;option value="&lt;?php echo iRange($id, 2, $format = 'm/d/Y' ) ?&gt;"&gt;"2 Days"&lt;/option&gt; &lt;option value="&lt;?php echo iRange($id, 3, $format = 'm/d/Y' ) ?&gt;"&gt;"3 Days"&lt;/option&gt; &lt;option value="&lt;?php echo iRange($id, 4, $format = 'm/d/Y' ) ?&gt;"&gt;"4 Days"&lt;/option&gt; &lt;/select&gt; &lt;?php}?&gt; </code></pre> <p>and here it is my js code <code>combo_checkout_iRange.js</code></p> <pre><code>$(document).ready(function() { $('#loader').hide(); $('#check-in-date').change(function(){ $('#check-out-date-wrap').fadeOut(); $('#loader').show(); $.post("combo_check-out.php", { parent_id: $('#check-in-date').val(), }, function(response){ setTimeout("finishAjax('check-out-date-wrap', '"+escape(response)+"')", 400); }); return false; }); }); //JQuery to hide Loader and return restults function finishAjax(id, response){ $('#loader').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } function alert_id() { if($('#check-out-date').val() == '') alert('Please select a sub category.'); else alert($("#check-out-date").val()); return false; } </code></pre> <p>they work fine outside wordpress</p> <p>how to integrate them in wordpress theme</p> <p><strong>Note:</strong> this should work in post type called "meetings" so this is what i wrote on <code>function.php</code></p> <pre><code>add_action("wp_enqueue_scripts", function() { if (is_single()) { if (get_post_type() == 'meetings') { wp_enqueue_script('combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array( 'jquery' ), '1.0' ,true); } } }); </code></pre>
[ { "answer_id": 181330, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>CSS is the answer. If you look at the HTML code of each row (<code>&lt;tr&gt;</code>), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags.</p>\n\n<p>For example, this is a row in one of my site:</p>\n\n<pre><code>&lt;tr id=\"post-24392\" class=\"post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0\"&gt;\n &lt;th scope=\"row\" class=\"check-column\"&gt;\n &lt;label class=\"screen-reader-text\" for=\"cb-select-24392\"&gt;Elige ¿?&lt;/label&gt;\n &lt;input id=\"cb-select-24392\" type=\"checkbox\" name=\"post[]\" value=\"24392\"&gt;\n &lt;div class=\"locked-indicator\"&gt;&lt;/div&gt;\n &lt;/th&gt;\n &lt;td class=\"post-title page-title column-title\"&gt;\n Here the title\n</code></pre>\n\n<p>If I want to change the color of the title if the post belongs to \"metro\" tag:</p>\n\n<pre><code>.tag-metro .post-title {\n color: red;\n}\n</code></pre>\n\n<p>You can put that CSS in a file and <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">enqueue it in admin</a>.</p>\n\n<p>If terms are from a custom taxonomy, you can hook post_class to add the classes based on the custom taxonomy:</p>\n\n<pre><code>add_filter( 'post_class', function( $classes, $class, $ID ) {\n\n $taxonomy = 'my-custom-taxonomy';\n\n $terms = get_the_terms( (int) $ID, $taxonomy );\n\n if( !empty( $terms ) ) {\n\n foreach( (array) $terms as $order =&gt; $term ) {\n\n if( !in_array( $term-&gt;slug, $classes ) ) {\n\n $classes[] = $term-&gt;slug;\n\n }\n\n }\n\n }\n\n return $classes;\n\n}, 10, 3 );\n</code></pre>\n" }, { "answer_id": 181334, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 0, "selected": false, "text": "<p>Unluckily does not exists a filter like that. However, output pass throught WordPress <em>usual</em> filters. E.g. <code>'the_title'</code> for title.</p>\n\n<p>The only problem is that you can't just add a filter to the <code>'the_title'</code>, because it will affect a lot of things. However you can use filters that are triggered only on post list admin screen (<code>edit.php</code>) to add the filter to title.</p>\n\n<p>As example:</p>\n\n<pre><code>// this filter is fired only on edit.php for 'post' post type\nadd_filter('manage_edit-post_sortable_columns', function($sortable) {\n\n // add a filter to post title. Use the lowest possible priority. \n add_filter('the_title', 'my_admin_title_color', PHP_INT_MAX);\n\n return $sortable;\n});\n\nfunction my_admin_title_color($title) {\n // you can use template tags or even access to global $post\n if ( has_category('uncategorized') ) {\n $title = '&lt;span style=\"color:#f00\"&gt;'.$title.'&lt;/span&gt;';\n }\n\n return $title;\n}\n</code></pre>\n\n<p>In code above I used <code>'manage_edit-post_sortable_columns'</code> because is a filter that is fired only on <code>edit.php</code> for 'post' post type.</p>\n\n<p>It is one of the <a href=\"https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/\" rel=\"nofollow\"><code>\"manage_{$screen_id}_sortable_columns\"</code></a>, filters that is triggered with a different name for different post types. As example you ca use <code>\"manage_edit-page_sortable_columns\"</code> to target pages. This <em>specificity</em> allow to add pretty safely the widely used <code>the_title</code> filter hook. Moreover by using a very low priority compatibility with other filters should be assured.</p>\n\n<p>After that you can just wrap the title with a span with some custom styles (as done in my example code), or some custom HTML class to be styles with external CSS.</p>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181354", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68426/" ]
I am trying to use ajax in wordpress I have two comboboxes in single-meetings.php the second combobox values are based on selection from the first one here is my `single-meetings.php` ``` <form action="#" name="form" id="form" method="post"> <div id="check-in-date-wrap"> <select name="search_category" id="check-in-date"> <option value="03/10/2015">"03/10/2015"</option> <option value="03/11/2015">"03/11/2015"</option> <option value="03/12/2015">"03/12/2015"</option> <option value="03/13/2015">"03/13/2015"</option> </select> <div id="check-out-date-wrap"> // a combobox should be created here </div> <img src="loader.gif" style="margin-top:8px; float:left" id="loader" alt="" /> <input type="submit" name="" value="GO" /> </form> ``` I have two another files, php and js this is my php code `combo_check-out.php` ``` <?php function iRange($first, $last, $format = 'm/d/Y' ) { $dates = array(); $current = strtotime($first); $i=1; while( $i <= $last ) { $dates[] = date($format, $current); $current = strtotime('+1 day', $current); $i++; } $time = date("m/d/Y",$current); return $time; } if($_REQUEST) { $id = $_REQUEST['parent_id']; ?> <select name="check-out" id="check-out-date"> <option value="<?php echo iRange($id, 1, $format = 'm/d/Y' ) ?>">"1 Day (Same Day)"</option> <option value="<?php echo iRange($id, 2, $format = 'm/d/Y' ) ?>">"2 Days"</option> <option value="<?php echo iRange($id, 3, $format = 'm/d/Y' ) ?>">"3 Days"</option> <option value="<?php echo iRange($id, 4, $format = 'm/d/Y' ) ?>">"4 Days"</option> </select> <?php}?> ``` and here it is my js code `combo_checkout_iRange.js` ``` $(document).ready(function() { $('#loader').hide(); $('#check-in-date').change(function(){ $('#check-out-date-wrap').fadeOut(); $('#loader').show(); $.post("combo_check-out.php", { parent_id: $('#check-in-date').val(), }, function(response){ setTimeout("finishAjax('check-out-date-wrap', '"+escape(response)+"')", 400); }); return false; }); }); //JQuery to hide Loader and return restults function finishAjax(id, response){ $('#loader').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } function alert_id() { if($('#check-out-date').val() == '') alert('Please select a sub category.'); else alert($("#check-out-date").val()); return false; } ``` they work fine outside wordpress how to integrate them in wordpress theme **Note:** this should work in post type called "meetings" so this is what i wrote on `function.php` ``` add_action("wp_enqueue_scripts", function() { if (is_single()) { if (get_post_type() == 'meetings') { wp_enqueue_script('combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array( 'jquery' ), '1.0' ,true); } } }); ```
CSS is the answer. If you look at the HTML code of each row (`<tr>`), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags. For example, this is a row in one of my site: ``` <tr id="post-24392" class="post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0"> <th scope="row" class="check-column"> <label class="screen-reader-text" for="cb-select-24392">Elige ¿?</label> <input id="cb-select-24392" type="checkbox" name="post[]" value="24392"> <div class="locked-indicator"></div> </th> <td class="post-title page-title column-title"> Here the title ``` If I want to change the color of the title if the post belongs to "metro" tag: ``` .tag-metro .post-title { color: red; } ``` You can put that CSS in a file and [enqueue it in admin](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts). If terms are from a custom taxonomy, you can hook post\_class to add the classes based on the custom taxonomy: ``` add_filter( 'post_class', function( $classes, $class, $ID ) { $taxonomy = 'my-custom-taxonomy'; $terms = get_the_terms( (int) $ID, $taxonomy ); if( !empty( $terms ) ) { foreach( (array) $terms as $order => $term ) { if( !in_array( $term->slug, $classes ) ) { $classes[] = $term->slug; } } } return $classes; }, 10, 3 ); ```
181,376
<p>I am trying to pull images as attachments from a particular post (custom post),</p> <p>...and I'm using the example within WordPress codex <a href="http://codex.wordpress.org/Function_Reference/wp_get_attachment_image#Display_all_images_as_a_list" rel="nofollow">codex example to display all images as a list</a></p> <p>...except the images in that post keep repeating about 3 or 4 times (I have a total of 7 images attached to that post). no matter what I set the numberposts to or the post_per_page, I keep getting repeated images, about 28 when I should only have the seven.</p> <p>If my numberposts is 1 or my post_per_image is 1 I only get 1 image of the 7 attached to that post... what am I doing wrong?</p> <p>The code I'm using is below, and an example of what's happening on my site is here <a href="http://www.ccbcreative.com/three-river/" rel="nofollow">my test site where i'm trying to pull images from a post to use within FlexSlider</a></p> <p>any help is very much appreciated. _Cindy</p> <pre><code>&lt;ul class="slides"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $args1 = array( 'post_type' =&gt; 'attachment', 'p = 107', 'numberposts' =&gt; 7, 'post_status' =&gt; 'inherit' ); $attachments = get_posts( $args1 ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo '&lt;li&gt;'; echo wp_get_attachment_image( $attachment-&gt;ID, 'home-slider' ); echo '&lt;/li&gt;'; } } endwhile; endif; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end 1080 pixels Container --&gt; &lt;div class="grid-gradient-bg"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- Slider Navigation --&gt; &lt;div id="home-hero-nav" role=""&gt; &lt;div class="container"&gt; &lt;!-- 1080 pixels Container --&gt; &lt;div class="full-width columns"&gt; &lt;ul class="slider-menu thumbnails clearfix"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $args2 = array( 'post_type' =&gt; 'attachment', 'p = 107', 'numberposts' =&gt; 0, 'post_status' =&gt; 'inherit' ); $attachments = get_posts( $args2 ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo '&lt;li&gt;'; echo wp_get_attachment_image( $attachment-&gt;ID, 'home-slider-thumb' ); echo '&lt;/li&gt;'; } } endwhile; endif; ?&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 181330, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>CSS is the answer. If you look at the HTML code of each row (<code>&lt;tr&gt;</code>), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags.</p>\n\n<p>For example, this is a row in one of my site:</p>\n\n<pre><code>&lt;tr id=\"post-24392\" class=\"post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0\"&gt;\n &lt;th scope=\"row\" class=\"check-column\"&gt;\n &lt;label class=\"screen-reader-text\" for=\"cb-select-24392\"&gt;Elige ¿?&lt;/label&gt;\n &lt;input id=\"cb-select-24392\" type=\"checkbox\" name=\"post[]\" value=\"24392\"&gt;\n &lt;div class=\"locked-indicator\"&gt;&lt;/div&gt;\n &lt;/th&gt;\n &lt;td class=\"post-title page-title column-title\"&gt;\n Here the title\n</code></pre>\n\n<p>If I want to change the color of the title if the post belongs to \"metro\" tag:</p>\n\n<pre><code>.tag-metro .post-title {\n color: red;\n}\n</code></pre>\n\n<p>You can put that CSS in a file and <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">enqueue it in admin</a>.</p>\n\n<p>If terms are from a custom taxonomy, you can hook post_class to add the classes based on the custom taxonomy:</p>\n\n<pre><code>add_filter( 'post_class', function( $classes, $class, $ID ) {\n\n $taxonomy = 'my-custom-taxonomy';\n\n $terms = get_the_terms( (int) $ID, $taxonomy );\n\n if( !empty( $terms ) ) {\n\n foreach( (array) $terms as $order =&gt; $term ) {\n\n if( !in_array( $term-&gt;slug, $classes ) ) {\n\n $classes[] = $term-&gt;slug;\n\n }\n\n }\n\n }\n\n return $classes;\n\n}, 10, 3 );\n</code></pre>\n" }, { "answer_id": 181334, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 0, "selected": false, "text": "<p>Unluckily does not exists a filter like that. However, output pass throught WordPress <em>usual</em> filters. E.g. <code>'the_title'</code> for title.</p>\n\n<p>The only problem is that you can't just add a filter to the <code>'the_title'</code>, because it will affect a lot of things. However you can use filters that are triggered only on post list admin screen (<code>edit.php</code>) to add the filter to title.</p>\n\n<p>As example:</p>\n\n<pre><code>// this filter is fired only on edit.php for 'post' post type\nadd_filter('manage_edit-post_sortable_columns', function($sortable) {\n\n // add a filter to post title. Use the lowest possible priority. \n add_filter('the_title', 'my_admin_title_color', PHP_INT_MAX);\n\n return $sortable;\n});\n\nfunction my_admin_title_color($title) {\n // you can use template tags or even access to global $post\n if ( has_category('uncategorized') ) {\n $title = '&lt;span style=\"color:#f00\"&gt;'.$title.'&lt;/span&gt;';\n }\n\n return $title;\n}\n</code></pre>\n\n<p>In code above I used <code>'manage_edit-post_sortable_columns'</code> because is a filter that is fired only on <code>edit.php</code> for 'post' post type.</p>\n\n<p>It is one of the <a href=\"https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/\" rel=\"nofollow\"><code>\"manage_{$screen_id}_sortable_columns\"</code></a>, filters that is triggered with a different name for different post types. As example you ca use <code>\"manage_edit-page_sortable_columns\"</code> to target pages. This <em>specificity</em> allow to add pretty safely the widely used <code>the_title</code> filter hook. Moreover by using a very low priority compatibility with other filters should be assured.</p>\n\n<p>After that you can just wrap the title with a span with some custom styles (as done in my example code), or some custom HTML class to be styles with external CSS.</p>\n" } ]
2015/03/16
[ "https://wordpress.stackexchange.com/questions/181376", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54520/" ]
I am trying to pull images as attachments from a particular post (custom post), ...and I'm using the example within WordPress codex [codex example to display all images as a list](http://codex.wordpress.org/Function_Reference/wp_get_attachment_image#Display_all_images_as_a_list) ...except the images in that post keep repeating about 3 or 4 times (I have a total of 7 images attached to that post). no matter what I set the numberposts to or the post\_per\_page, I keep getting repeated images, about 28 when I should only have the seven. If my numberposts is 1 or my post\_per\_image is 1 I only get 1 image of the 7 attached to that post... what am I doing wrong? The code I'm using is below, and an example of what's happening on my site is here [my test site where i'm trying to pull images from a post to use within FlexSlider](http://www.ccbcreative.com/three-river/) any help is very much appreciated. \_Cindy ``` <ul class="slides"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $args1 = array( 'post_type' => 'attachment', 'p = 107', 'numberposts' => 7, 'post_status' => 'inherit' ); $attachments = get_posts( $args1 ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo '<li>'; echo wp_get_attachment_image( $attachment->ID, 'home-slider' ); echo '</li>'; } } endwhile; endif; ?> </ul> </div> </div> </div> </div> <!-- end 1080 pixels Container --> <div class="grid-gradient-bg"></div> </div> <!-- Slider Navigation --> <div id="home-hero-nav" role=""> <div class="container"> <!-- 1080 pixels Container --> <div class="full-width columns"> <ul class="slider-menu thumbnails clearfix"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $args2 = array( 'post_type' => 'attachment', 'p = 107', 'numberposts' => 0, 'post_status' => 'inherit' ); $attachments = get_posts( $args2 ); if ( $attachments ) { foreach ( $attachments as $attachment ) { echo '<li>'; echo wp_get_attachment_image( $attachment->ID, 'home-slider-thumb' ); echo '</li>'; } } endwhile; endif; ?> </ul> ```
CSS is the answer. If you look at the HTML code of each row (`<tr>`), you will see that it has classes that include post ID, post status, post tags, categories, and so on. So, you can easily apply CSS rules based on that classes and based on post tags. For example, this is a row in one of my site: ``` <tr id="post-24392" class="post-24392 type-post status-publish format-standard has-post-thumbnail hentry category-ciencia-y-tecnologia tag-distancia tag-longitud tag-metro tag-sistema-internacional-de-unidades alternate iedit author-other level-0"> <th scope="row" class="check-column"> <label class="screen-reader-text" for="cb-select-24392">Elige ¿?</label> <input id="cb-select-24392" type="checkbox" name="post[]" value="24392"> <div class="locked-indicator"></div> </th> <td class="post-title page-title column-title"> Here the title ``` If I want to change the color of the title if the post belongs to "metro" tag: ``` .tag-metro .post-title { color: red; } ``` You can put that CSS in a file and [enqueue it in admin](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts). If terms are from a custom taxonomy, you can hook post\_class to add the classes based on the custom taxonomy: ``` add_filter( 'post_class', function( $classes, $class, $ID ) { $taxonomy = 'my-custom-taxonomy'; $terms = get_the_terms( (int) $ID, $taxonomy ); if( !empty( $terms ) ) { foreach( (array) $terms as $order => $term ) { if( !in_array( $term->slug, $classes ) ) { $classes[] = $term->slug; } } } return $classes; }, 10, 3 ); ```
181,381
<p>I have the following query but it is still returning results which include posts which have a meta value of 'deal'.</p> <p>Any Clues on what am i missing in this </p> <pre><code> $args = array( 'post_type' =&gt; POST_TYPE, 'meta_key' =&gt; 'is_hot', 'meta_value' =&gt; '1', 'meta_compare' =&gt; '=', 'posts_per_page' =&gt; 20, 'no_found_rows' =&gt; true, 'suppress_filters' =&gt; false, 'meta_key' =&gt; 'offer_type', 'meta_value' =&gt; 'deal', 'meta_compare' =&gt; 'NOT LIKE', ), ); new WP_Query( $args ); </code></pre>
[ { "answer_id": 181384, "author": "grandcoder", "author_id": 69121, "author_profile": "https://wordpress.stackexchange.com/users/69121", "pm_score": 1, "selected": false, "text": "<p><code>meta_compare</code> possible values are </p>\n\n<blockquote>\n <p>'!=', '>', '>=', '&lt;', or ='. Default value is '='</p>\n</blockquote>\n\n<p>if you want to use <code>NOT LIKE</code> you need to create a meta_query.</p>\n\n<p>example</p>\n\n<pre><code>'meta_query' =&gt; array( //(array) - Custom field parameters (available with Version 3.1).\n array(\n 'key' =&gt; 'color', //(string) - Custom field key.\n 'value' =&gt; 'blue' //(string/array) - Custom field value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN')\n 'type' =&gt; 'CHAR', //(string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'.\n 'compare' =&gt; '=' //(string) - Operator to test. Possible values are '=', '!=', '&gt;', '&gt;=', '&lt;', '&lt;=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default value is '='.\n ),\n array(\n 'key' =&gt; 'price',\n 'value' =&gt; array( 1,200 ),\n 'compare' =&gt; 'NOT LIKE'\n ))\n</code></pre>\n" }, { "answer_id": 181402, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>You can not query for multiple meta fields using <code>meta_key</code> and <code>meta_value</code> parameters, you have to use <code>meta_query</code> parameter. Using multiple <code>meta_key</code> and <code>meta_value</code> parameters will use only the first found pair, that is why in your code the condition about &quot;offer_type NOT LIKE deal&quot; is ignored.</p>\n<p>So, the correct query should be:</p>\n<pre><code>$args = array(\n\n 'post_type' =&gt; POST_TYPE,\n 'posts_per_page' =&gt; 20,\n 'no_found_rows' =&gt; true,\n 'suppress_filters' =&gt; false,\n //Se the meta query\n 'meta_query' =&gt; array(\n //comparison between the inner meta fields conditionals\n 'relation' =&gt; 'AND',\n //meta field's first condition\n array(\n 'key' =&gt; 'is_hot',\n 'value' =&gt; '1',\n 'compare' =&gt; '=',\n ),\n //meta field's second condition\n array(\n 'key' =&gt; 'offer_type',\n 'value' =&gt; 'deal',\n //I think you really want != instead of NOT LIKE, fix me if I'm wrong\n //'compare' =&gt; 'NOT LIKE',\n 'compare' =&gt; '!=',\n )\n ),\n\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n" } ]
2015/03/17
[ "https://wordpress.stackexchange.com/questions/181381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52047/" ]
I have the following query but it is still returning results which include posts which have a meta value of 'deal'. Any Clues on what am i missing in this ``` $args = array( 'post_type' => POST_TYPE, 'meta_key' => 'is_hot', 'meta_value' => '1', 'meta_compare' => '=', 'posts_per_page' => 20, 'no_found_rows' => true, 'suppress_filters' => false, 'meta_key' => 'offer_type', 'meta_value' => 'deal', 'meta_compare' => 'NOT LIKE', ), ); new WP_Query( $args ); ```
You can not query for multiple meta fields using `meta_key` and `meta_value` parameters, you have to use `meta_query` parameter. Using multiple `meta_key` and `meta_value` parameters will use only the first found pair, that is why in your code the condition about "offer\_type NOT LIKE deal" is ignored. So, the correct query should be: ``` $args = array( 'post_type' => POST_TYPE, 'posts_per_page' => 20, 'no_found_rows' => true, 'suppress_filters' => false, //Se the meta query 'meta_query' => array( //comparison between the inner meta fields conditionals 'relation' => 'AND', //meta field's first condition array( 'key' => 'is_hot', 'value' => '1', 'compare' => '=', ), //meta field's second condition array( 'key' => 'offer_type', 'value' => 'deal', //I think you really want != instead of NOT LIKE, fix me if I'm wrong //'compare' => 'NOT LIKE', 'compare' => '!=', ) ), ); $query = new WP_Query( $args ); ```
181,386
<p>My primary website on a multisite network was created with the <code>www</code> prefix (like <code>www.example.com</code>).</p> <p>If I try to access pages without the <code>www</code> prefix (like <code>example.com/page-name/</code> instead of <code>www.example.com/page-name/</code>, I am redirected to the homepage (<code>www.example.com</code>). I would like to change this so I am redirected simply redirected to the same page URL, only with the <code>www</code> prefix.</p> <p>Additionally, the 404 error page doesn't work on the primary site. No matter which non-existant URL I try (such as <code>www.example.com/thisdoesnotexist</code>), I am always redirected to the primary site home page (<code>www.example.com</code>), rather then seeing the theme's 404 page.</p> <p>Here is a <a href="http://www.ncc.my" rel="nofollow">link to my site</a> where you can test the issue.</p>
[ { "answer_id": 181401, "author": "Shreyo Gi", "author_id": 65741, "author_profile": "https://wordpress.stackexchange.com/users/65741", "pm_score": 0, "selected": false, "text": "<p>check your <code>.htaccess</code> for </p>\n\n<p><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;</code></p>\n\n<p>this is the basic htaccesss parameters a wordpress installation creates during installation. Line no. 3 is important.</p>\n\n<ol start=\"2\">\n<li>Check your database options table for proper siteurl and home value for <a href=\"http://www.yourdomainname.com\" rel=\"nofollow\">http://www.yourdomainname.com</a>.</li>\n</ol>\n" }, { "answer_id": 181739, "author": "shea", "author_id": 19726, "author_profile": "https://wordpress.stackexchange.com/users/19726", "pm_score": 4, "selected": true, "text": "<p>There is currently a bug in the functionality that handles the <code>NOBLOGREDIRECT</code> constant, which causes 404 errors on the main site to be redirected to the value of the constant. Apparently this is the expected behaviour for sub-directory networks (<code>example.com/subsite</code>), but should not take place on subdomain networks (<code>subsite.example.com</code>).</p>\n\n<p>There is a <a href=\"https://core.trac.wordpress.org/ticket/21573\" rel=\"noreferrer\">WordPress Trac ticket (#21573)</a> concerning this bug, but there is no indication on when it might be resolved. Until then, you can resolve this error yourself by removing the <code>maybe_redirect_404</code> function:</p>\n\n<pre><code>remove_action( 'template_redirect', 'maybe_redirect_404' );\n</code></pre>\n\n<p>This code should go in a <code>.php</code> file in the <code>wp-content/mu-plugins</code> directory. Remember to include a <code>&lt;?php</code> tag at the beginning of the file.</p>\n" } ]
2015/03/17
[ "https://wordpress.stackexchange.com/questions/181386", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23036/" ]
My primary website on a multisite network was created with the `www` prefix (like `www.example.com`). If I try to access pages without the `www` prefix (like `example.com/page-name/` instead of `www.example.com/page-name/`, I am redirected to the homepage (`www.example.com`). I would like to change this so I am redirected simply redirected to the same page URL, only with the `www` prefix. Additionally, the 404 error page doesn't work on the primary site. No matter which non-existant URL I try (such as `www.example.com/thisdoesnotexist`), I am always redirected to the primary site home page (`www.example.com`), rather then seeing the theme's 404 page. Here is a [link to my site](http://www.ncc.my) where you can test the issue.
There is currently a bug in the functionality that handles the `NOBLOGREDIRECT` constant, which causes 404 errors on the main site to be redirected to the value of the constant. Apparently this is the expected behaviour for sub-directory networks (`example.com/subsite`), but should not take place on subdomain networks (`subsite.example.com`). There is a [WordPress Trac ticket (#21573)](https://core.trac.wordpress.org/ticket/21573) concerning this bug, but there is no indication on when it might be resolved. Until then, you can resolve this error yourself by removing the `maybe_redirect_404` function: ``` remove_action( 'template_redirect', 'maybe_redirect_404' ); ``` This code should go in a `.php` file in the `wp-content/mu-plugins` directory. Remember to include a `<?php` tag at the beginning of the file.
181,394
<p>I an creating a custom plugin that used shortcodes.. then it will have a feature that will upload files and stores it in <code>wp-content/uploads/</code> directory.. but it seems I got an error..</p> <pre><code>Warning: move_uploaded_file(http://mysitecom/wp-content/uploads/myfiles/1991117- DriverLiscence.jpg): failed to open stream: HTTP wrapper does not support writeable connections in /home/user/public_html/mysite/wp-content/plugins/myplugin/functions.php on line 1266 Warning: move_uploaded_file(): Unable to move '/tmp/phpOOkdNJ' to 'http://mysitecom/wp-content/uploads/myfiles/1991117-DriverLiscence.jpg' in /home/user/public_html/mysite/wp-content/plugins/myplugin/functions.php on line 1266 </code></pre> <p>this is the code:</p> <pre><code>$upload_dir = wp_upload_dir(); $wp_upload_url =$upload_dir['baseurl']; $uploaddir = $wp_upload_url."/myfiles/"; $temp = explode(".",$_FILES[$file_uploaded]["name"]); $newfilename = $contactID. '-'. $type . '.' .end($temp); $uploadfile = $uploaddir . $newfilename; if (move_uploaded_file($_FILES[$file_uploaded]['tmp_name'], $uploadfile)) { echo 'success'; } </code></pre> <p>ny question is that, how can I get the exact path of the <code>/wp-content/uploads/myfiles/</code> so that I can upload files?</p>
[ { "answer_id": 181395, "author": "grandcoder", "author_id": 69121, "author_profile": "https://wordpress.stackexchange.com/users/69121", "pm_score": 0, "selected": false, "text": "<p>You cannot move a file over HTTP, instead you need to move it using local path.</p>\n\n<pre><code>(e.g. /home/content/site/folders/filename.php).\n</code></pre>\n\n<p>normally people upload files to media library. The following code shows how to upload a file from a plugin.</p>\n\n<pre><code>if ($_FILES) {\n foreach ($_FILES as $file =&gt; $array) {\n if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {\n return \"upload error : \" . $_FILES[$file]['error'];\n }\n $attach_id = media_handle_upload( $file, 0 );\n } \n}\n</code></pre>\n" }, { "answer_id": 191990, "author": "Rutunj sheladiya", "author_id": 74824, "author_profile": "https://wordpress.stackexchange.com/users/74824", "pm_score": 1, "selected": false, "text": "<p>Use Wordpress defult media uploader and get uploaded link in jquery response it is quit easy </p>\n\n<pre><code>&lt;label for=\"upload_image\"&gt;\n &lt;input id=\"upload_image\" type=\"text\" size=\"36\" name=\"ad_image\" value=\"http://\" /&gt; \n &lt;input id=\"upload_image_button\" class=\"button\" type=\"button\" value=\"Upload Image\" /&gt;\n &lt;br /&gt;Enter a URL or upload an image\n&lt;/label&gt;\n\n&lt;?php\nadd_action('admin_enqueue_scripts', 'my_admin_scripts');\n\nfunction my_admin_scripts() {\n if (isset($_GET['page']) &amp;&amp; $_GET['page'] == 'my_plugin_page') {\n wp_enqueue_media();\n wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery'));\n wp_enqueue_script('my-admin-js');\n }\n}\n\n?&gt;\n\n&lt;script&gt;\n jQuery(document).ready(function($){\n\n\n var custom_uploader;\n\n\n $('#upload_image_button').click(function(e) {\n\n e.preventDefault();\n\n //If the uploader object has already been created, reopen the dialog\n if (custom_uploader) {\n custom_uploader.open();\n return;\n }\n\n //Extend the wp.media object\n custom_uploader = wp.media.frames.file_frame = wp.media({\n title: 'Choose Image',\n button: {\n text: 'Choose Image'\n },\n multiple: true\n });\n\n //When a file is selected, grab the URL and set it as the text field's value\n custom_uploader.on('select', function() {\n console.log(custom_uploader.state().get('selection').toJSON());\n attachment = custom_uploader.state().get('selection').first().toJSON();\n $('#upload_image').val(attachment.url);\n });\n\n //Open the uploader dialog\n custom_uploader.open();\n\n });\n\n\n});\n &lt;/script&gt;\n</code></pre>\n" } ]
2015/03/17
[ "https://wordpress.stackexchange.com/questions/181394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68933/" ]
I an creating a custom plugin that used shortcodes.. then it will have a feature that will upload files and stores it in `wp-content/uploads/` directory.. but it seems I got an error.. ``` Warning: move_uploaded_file(http://mysitecom/wp-content/uploads/myfiles/1991117- DriverLiscence.jpg): failed to open stream: HTTP wrapper does not support writeable connections in /home/user/public_html/mysite/wp-content/plugins/myplugin/functions.php on line 1266 Warning: move_uploaded_file(): Unable to move '/tmp/phpOOkdNJ' to 'http://mysitecom/wp-content/uploads/myfiles/1991117-DriverLiscence.jpg' in /home/user/public_html/mysite/wp-content/plugins/myplugin/functions.php on line 1266 ``` this is the code: ``` $upload_dir = wp_upload_dir(); $wp_upload_url =$upload_dir['baseurl']; $uploaddir = $wp_upload_url."/myfiles/"; $temp = explode(".",$_FILES[$file_uploaded]["name"]); $newfilename = $contactID. '-'. $type . '.' .end($temp); $uploadfile = $uploaddir . $newfilename; if (move_uploaded_file($_FILES[$file_uploaded]['tmp_name'], $uploadfile)) { echo 'success'; } ``` ny question is that, how can I get the exact path of the `/wp-content/uploads/myfiles/` so that I can upload files?
Use Wordpress defult media uploader and get uploaded link in jquery response it is quit easy ``` <label for="upload_image"> <input id="upload_image" type="text" size="36" name="ad_image" value="http://" /> <input id="upload_image_button" class="button" type="button" value="Upload Image" /> <br />Enter a URL or upload an image </label> <?php add_action('admin_enqueue_scripts', 'my_admin_scripts'); function my_admin_scripts() { if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') { wp_enqueue_media(); wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery')); wp_enqueue_script('my-admin-js'); } } ?> <script> jQuery(document).ready(function($){ var custom_uploader; $('#upload_image_button').click(function(e) { e.preventDefault(); //If the uploader object has already been created, reopen the dialog if (custom_uploader) { custom_uploader.open(); return; } //Extend the wp.media object custom_uploader = wp.media.frames.file_frame = wp.media({ title: 'Choose Image', button: { text: 'Choose Image' }, multiple: true }); //When a file is selected, grab the URL and set it as the text field's value custom_uploader.on('select', function() { console.log(custom_uploader.state().get('selection').toJSON()); attachment = custom_uploader.state().get('selection').first().toJSON(); $('#upload_image').val(attachment.url); }); //Open the uploader dialog custom_uploader.open(); }); }); </script> ```
181,452
<p>I am working with redux framework and need to save theme option values to a file right before it is saved in DB. Is there a way to intercept</p> <pre><code>update_option() </code></pre> <p>right before it saves data in DB?</p>
[ { "answer_id": 181455, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>There is a filter exactly for that: <code>pre_update_option_{option_name}</code>. If the is option is, for example, names <code>myoption</code>, you could use somthing like this:</p>\n\n<pre><code>add_filter( 'pre_update_option_myoption', function( $new_value, $old_value ) {\n\n //Do something before returning the new value to be saved in database\n\n return $new_value;\n\n}, 10, 2);\n</code></pre>\n\n<p>Referene: <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/pre_update_option_(option_name)\" rel=\"nofollow\">pre_update_option_(option_name)</a></p>\n\n<p>It would be useful a general <code>pre_update_option</code> for all options, but as far I know such filter doesn't exist.</p>\n\n<p>You asked about someting to use <em>right before</em> the option is saved to DB but you may be also interested in <code>update_option_{option_name}</code> action. This action is fired <em>right after</em> the option has been saved. Please, note that <code>update_option_{option_name}</code> is an action while <code>pre_update_option_{option_name}</code> is a filter, both are intented for different things. Basically (very basically), actions are intended to perform tasks and don't <code>return</code> values; filters <code>return</code> values and they are intented to work with or modify data (although there is nothing that stop you to perform tasks in filters).</p>\n" }, { "answer_id": 181522, "author": "DiverseAndRemote.com", "author_id": 23690, "author_profile": "https://wordpress.stackexchange.com/users/23690", "pm_score": 3, "selected": true, "text": "<p>You might be better off using the <code>update_option_</code> action instead. This will allow you to write to your file after the option has been updated (as apposed to before). If another plugin hooks into pre_update_option_ and alters the value after your plugin has saved it then you will have saved an incorrect value.</p>\n\n<p>I would use:</p>\n\n<pre><code>add_action( 'update_option_myoption', function( $old_value, $new_value ) {\n //Do something with the new value\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 185301, "author": "Dovy", "author_id": 44585, "author_profile": "https://wordpress.stackexchange.com/users/44585", "pm_score": 0, "selected": false, "text": "<p>Lead dev of Redux here. You can use one of our filters to match your needs:</p>\n\n<p>\"redux/validate/{$this->args['opt_name']}/defaults\" - Only on resetting defaults</p>\n\n<p>\"redux/validate/{$this->args['opt_name']}/defaults_section\" - Only on resetting one section</p>\n\n<p>\"redux/options/{$this->args['opt_name']}/import\" - Only on import</p>\n\n<p>\"redux/validate/{$this->args['opt_name']}/before_validation\" - before validation</p>\n\n<p>\"redux/options/{$this->args['opt_name']}/validate\" - after validation</p>\n" } ]
2015/03/17
[ "https://wordpress.stackexchange.com/questions/181452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67176/" ]
I am working with redux framework and need to save theme option values to a file right before it is saved in DB. Is there a way to intercept ``` update_option() ``` right before it saves data in DB?
You might be better off using the `update_option_` action instead. This will allow you to write to your file after the option has been updated (as apposed to before). If another plugin hooks into pre\_update\_option\_ and alters the value after your plugin has saved it then you will have saved an incorrect value. I would use: ``` add_action( 'update_option_myoption', function( $old_value, $new_value ) { //Do something with the new value }, 10, 2); ```
181,454
<p>I have a working Lightbox (colorbox) solution for my wordpress images. However I would like to add a custom title based on the image caption and photographer name to the lightbox image. </p> <p>This works perfectly when adding a title attribute to the image link.</p> <p>However, how do I add the image caption to the image link. </p> <p>So that :</p> <pre><code>&lt;a href="link-to-attachment.jpg" rel="img-lightbox"&gt;&lt;img..&gt;&lt;/a&gt; </code></pre> <p>becomes</p> <pre><code>&lt;a href="link-to-attachment.jpg" title="caption of the image" rel="img-lightbox"&gt;&lt;img..&gt;&lt;/a&gt; </code></pre> <p>For adding the correct rel and class attributes and values I used the the_content filter. </p> <p>This way I can add default values which are the same for all images. However for the lightbox caption I also need to know which attachment image link I am changing to create the correct caption. Therefor the_content doesn;t seem usable it just changes all a hrefs without knowing which link is related to which attachment id exactly.</p> <p>I found a lot of solutions using the wp_get_attachment_link filter. But I cannot seem to get this working. </p> <p>I am hoping I am making a simple mistake. When starting basic: I just added the filter which does nothing more than logging something and return the original value.</p> <p>Problem is that the filter does not seemed to be called on the page which contains images.</p> <p>The following code doesn's seem to do anything. I added it to my functions.php</p> <pre><code>function add_rel_to_gallery($link, $id) { error_log("SIMPLE TEST"); return $link; } add_filter( 'wp_get_attachment_link', 'add_rel_to_gallery', 10, 2 ); </code></pre> <p>What am I doing wrong? Or any suggestions how to solve this issue?</p>
[ { "answer_id": 181455, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>There is a filter exactly for that: <code>pre_update_option_{option_name}</code>. If the is option is, for example, names <code>myoption</code>, you could use somthing like this:</p>\n\n<pre><code>add_filter( 'pre_update_option_myoption', function( $new_value, $old_value ) {\n\n //Do something before returning the new value to be saved in database\n\n return $new_value;\n\n}, 10, 2);\n</code></pre>\n\n<p>Referene: <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/pre_update_option_(option_name)\" rel=\"nofollow\">pre_update_option_(option_name)</a></p>\n\n<p>It would be useful a general <code>pre_update_option</code> for all options, but as far I know such filter doesn't exist.</p>\n\n<p>You asked about someting to use <em>right before</em> the option is saved to DB but you may be also interested in <code>update_option_{option_name}</code> action. This action is fired <em>right after</em> the option has been saved. Please, note that <code>update_option_{option_name}</code> is an action while <code>pre_update_option_{option_name}</code> is a filter, both are intented for different things. Basically (very basically), actions are intended to perform tasks and don't <code>return</code> values; filters <code>return</code> values and they are intented to work with or modify data (although there is nothing that stop you to perform tasks in filters).</p>\n" }, { "answer_id": 181522, "author": "DiverseAndRemote.com", "author_id": 23690, "author_profile": "https://wordpress.stackexchange.com/users/23690", "pm_score": 3, "selected": true, "text": "<p>You might be better off using the <code>update_option_</code> action instead. This will allow you to write to your file after the option has been updated (as apposed to before). If another plugin hooks into pre_update_option_ and alters the value after your plugin has saved it then you will have saved an incorrect value.</p>\n\n<p>I would use:</p>\n\n<pre><code>add_action( 'update_option_myoption', function( $old_value, $new_value ) {\n //Do something with the new value\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 185301, "author": "Dovy", "author_id": 44585, "author_profile": "https://wordpress.stackexchange.com/users/44585", "pm_score": 0, "selected": false, "text": "<p>Lead dev of Redux here. You can use one of our filters to match your needs:</p>\n\n<p>\"redux/validate/{$this->args['opt_name']}/defaults\" - Only on resetting defaults</p>\n\n<p>\"redux/validate/{$this->args['opt_name']}/defaults_section\" - Only on resetting one section</p>\n\n<p>\"redux/options/{$this->args['opt_name']}/import\" - Only on import</p>\n\n<p>\"redux/validate/{$this->args['opt_name']}/before_validation\" - before validation</p>\n\n<p>\"redux/options/{$this->args['opt_name']}/validate\" - after validation</p>\n" } ]
2015/03/17
[ "https://wordpress.stackexchange.com/questions/181454", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65287/" ]
I have a working Lightbox (colorbox) solution for my wordpress images. However I would like to add a custom title based on the image caption and photographer name to the lightbox image. This works perfectly when adding a title attribute to the image link. However, how do I add the image caption to the image link. So that : ``` <a href="link-to-attachment.jpg" rel="img-lightbox"><img..></a> ``` becomes ``` <a href="link-to-attachment.jpg" title="caption of the image" rel="img-lightbox"><img..></a> ``` For adding the correct rel and class attributes and values I used the the\_content filter. This way I can add default values which are the same for all images. However for the lightbox caption I also need to know which attachment image link I am changing to create the correct caption. Therefor the\_content doesn;t seem usable it just changes all a hrefs without knowing which link is related to which attachment id exactly. I found a lot of solutions using the wp\_get\_attachment\_link filter. But I cannot seem to get this working. I am hoping I am making a simple mistake. When starting basic: I just added the filter which does nothing more than logging something and return the original value. Problem is that the filter does not seemed to be called on the page which contains images. The following code doesn's seem to do anything. I added it to my functions.php ``` function add_rel_to_gallery($link, $id) { error_log("SIMPLE TEST"); return $link; } add_filter( 'wp_get_attachment_link', 'add_rel_to_gallery', 10, 2 ); ``` What am I doing wrong? Or any suggestions how to solve this issue?
You might be better off using the `update_option_` action instead. This will allow you to write to your file after the option has been updated (as apposed to before). If another plugin hooks into pre\_update\_option\_ and alters the value after your plugin has saved it then you will have saved an incorrect value. I would use: ``` add_action( 'update_option_myoption', function( $old_value, $new_value ) { //Do something with the new value }, 10, 2); ```
181,496
<p>My function lets users delete their uploaded images in the front-end. However, they're only deleted in the Media Library. That means that they're still in wp-content/uploads/.</p> <pre><code>public static function removePhoto($ID, $attachment) { if(isset(self::$data['user']['photos'][$attachment])) { unset(self::$data['user']['photos'][$attachment]); wp_delete_attachment($attachment); core:updateUserMeta($ID, 'photos', self::$data['user']['photos']); } } </code></pre> <p>This is how how the images are added:</p> <pre><code>public static function uploadImage($file) { require_once(ABSPATH.'wp-admin/includes/image.php'); $attachment=array('ID' =&gt; 0); if(JBSUser::$data['user']['membership']['photos']&lt;=0) { JBSInterface::$messages[]=__('You have exceeded the number of photos', 'epic'); return $file; } if(!empty($file['name'])) { $uploads=wp_upload_dir(); $filetype=wp_check_filetype($file['name'], null); $filename=wp_unique_filename($uploads['path'], 'image-1.'.$filetype['ext']); $filepath=$uploads['path'].'/'.$filename; //validate file if (!in_array($filetype['ext'], array('jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG'))) { JBSInterface::$messages[]=__('Only JPG and PNG images are allowed.', 'epic'); } else if(move_uploaded_file($file['tmp_name'], $filepath)) { //upload image $attachment=array( 'guid' =&gt; $uploads['url'].'/'.$filename, 'post_mime_type' =&gt; $filetype['type'], 'post_title' =&gt; sanitize_title(current(explode('.', $filename))), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'post_author' =&gt; get_current_user_id(), ); //add image $attachment['ID']=wp_insert_attachment($attachment, $attachment['guid'], 0); update_post_meta($attachment['ID'], '_wp_attached_file', substr($uploads['subdir'], 1).'/'.$filename); //add thumbnails $metadata=wp_generate_attachment_metadata($attachment['ID'], $filepath); wp_update_attachment_metadata($attachment['ID'], $metadata); } else { JBSInterface::$messages[]=__('This image is too large for uploading.','epic'); } } return $attachment; } </code></pre> <p>Update: Setting <code>wp_delete_attachment</code>, <code>true</code> - does not work.</p> <p>I'm suspicious of: <code>substr($uploads['subdir'], 1).'/'.$filename);</code> Which seems to upload the files to subfolder. But the images are still uploaded to the wp-content/uploads/ regardless if the &quot;organize&quot; setting is on or off.</p> <p>Should this really effect the wp_delete_attachment?</p>
[ { "answer_id": 181518, "author": "DiverseAndRemote.com", "author_id": 23690, "author_profile": "https://wordpress.stackexchange.com/users/23690", "pm_score": 0, "selected": false, "text": "<p>You need to provide <a href=\"http://codex.wordpress.org/Function_Reference/wp_delete_attachment\" rel=\"nofollow\">wp_delete_attachment</a> a value of true for it's second argument <code>force_delete</code>. Your code needs to change to <code>wp_delete_attachment( $attachment, true );</code></p>\n" }, { "answer_id": 181519, "author": "grandcoder", "author_id": 69121, "author_profile": "https://wordpress.stackexchange.com/users/69121", "pm_score": 0, "selected": false, "text": "<p>You forgot to add second parameter for the function <a href=\"http://codex.wordpress.org/Function_Reference/wp_delete_attachment\" rel=\"nofollow\">wp_delete_attachment</a></p>\n\n<pre><code> &lt;?php wp_delete_attachment( $attachmentid, $force_delete ); ?&gt; \n</code></pre>\n\n<blockquote>\n <p>$attachmentid <BR>\n (integer) (required) The ID of the attachment you would\n like to delete. <BR>Default: None</p>\n \n <p>$force_delete (bool) (optional) Whether to bypass trash and force\n deletion (added in WordPress 2.9). <br> Default: false</p>\n</blockquote>\n" }, { "answer_id": 360671, "author": "Tofandel", "author_id": 118064, "author_profile": "https://wordpress.stackexchange.com/users/118064", "pm_score": 2, "selected": false, "text": "<p>For future reference, if your attachment gets deleted but not your files</p>\n\n<p>There is a filter <code>wp_delete_file</code>, check if this filter is hooked on somewhere, if it returns <code>null</code> your file won't be deleted but the attachment will</p>\n\n<p>For me it was due to the WPML plugin, they duplicate attachments and then checks that all the attachments are deleted before actually deleting the file</p>\n\n<p>You can either add this action in your theme/plugin, that will delete all translations when using <code>$force_delete</code> in <code>wp_delete_attachment</code></p>\n\n<pre><code>if ( ! function_exists( 'delete_attachment_translations' ) ) {\n function delete_attachment_translations( $id ) {\n remove_action( 'delete_attachment', 'delete_attachment_translations' );\n\n $langs = apply_filters( 'wpml_active_languages', [] );\n\n if ( ! empty( $langs ) ) {\n global $wp_filter;\n\n //We need to temporarly remove WPML's hook or they will cache the result and not delete the file\n // Sadly they used a filter on a non global class instance, so we cannot access it via regular wp hook\n $hooks = $wp_filter['wp_delete_file']-&gt;callbacks[10];\n unset( $wp_filter['wp_delete_file']-&gt;callbacks[10] );\n\n foreach ( $langs as $code =&gt; $info ) {\n $post_id = apply_filters( 'wpml_object_id', $id, 'attachment', false, $code );\n if ( $id == $post_id ) {\n continue;\n }\n wp_delete_attachment( $post_id, true );\n }\n\n $wp_filter['wp_delete_file']-&gt;callbacks[10] = $hooks;\n }\n\n add_action( 'delete_attachment', 'delete_attachment_translations' );\n }\n\n add_action( 'delete_attachment', 'delete_attachment_translations' );\n}\n</code></pre>\n\n<p>Or check this option in your WPML settings (But it applies to all posts types, not just attachments)</p>\n\n<p><a href=\"https://i.stack.imgur.com/hnthm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hnthm.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 366571, "author": "Calara Ionut", "author_id": 51046, "author_profile": "https://wordpress.stackexchange.com/users/51046", "pm_score": 0, "selected": false, "text": "<p>Inside the <code>wp-includes/post.php</code> in the <code>wp_delete_attachment_files</code> there's a check to see if other attachments use the same file. This is what was happening in my case. Because I initially deleted the file manually but not the attachment, when I was uploading it again, the same name as before was used. </p>\n\n<p>So when the delete function was called for the newly uploaded attachment id, the old attachment had a reference to the same file, so the DB attachment was deleted and not the file. </p>\n\n<p>Make sure you manually delete all the attachments that could point to the same file from the media library. </p>\n" } ]
2015/03/17
[ "https://wordpress.stackexchange.com/questions/181496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45127/" ]
My function lets users delete their uploaded images in the front-end. However, they're only deleted in the Media Library. That means that they're still in wp-content/uploads/. ``` public static function removePhoto($ID, $attachment) { if(isset(self::$data['user']['photos'][$attachment])) { unset(self::$data['user']['photos'][$attachment]); wp_delete_attachment($attachment); core:updateUserMeta($ID, 'photos', self::$data['user']['photos']); } } ``` This is how how the images are added: ``` public static function uploadImage($file) { require_once(ABSPATH.'wp-admin/includes/image.php'); $attachment=array('ID' => 0); if(JBSUser::$data['user']['membership']['photos']<=0) { JBSInterface::$messages[]=__('You have exceeded the number of photos', 'epic'); return $file; } if(!empty($file['name'])) { $uploads=wp_upload_dir(); $filetype=wp_check_filetype($file['name'], null); $filename=wp_unique_filename($uploads['path'], 'image-1.'.$filetype['ext']); $filepath=$uploads['path'].'/'.$filename; //validate file if (!in_array($filetype['ext'], array('jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG'))) { JBSInterface::$messages[]=__('Only JPG and PNG images are allowed.', 'epic'); } else if(move_uploaded_file($file['tmp_name'], $filepath)) { //upload image $attachment=array( 'guid' => $uploads['url'].'/'.$filename, 'post_mime_type' => $filetype['type'], 'post_title' => sanitize_title(current(explode('.', $filename))), 'post_content' => '', 'post_status' => 'inherit', 'post_author' => get_current_user_id(), ); //add image $attachment['ID']=wp_insert_attachment($attachment, $attachment['guid'], 0); update_post_meta($attachment['ID'], '_wp_attached_file', substr($uploads['subdir'], 1).'/'.$filename); //add thumbnails $metadata=wp_generate_attachment_metadata($attachment['ID'], $filepath); wp_update_attachment_metadata($attachment['ID'], $metadata); } else { JBSInterface::$messages[]=__('This image is too large for uploading.','epic'); } } return $attachment; } ``` Update: Setting `wp_delete_attachment`, `true` - does not work. I'm suspicious of: `substr($uploads['subdir'], 1).'/'.$filename);` Which seems to upload the files to subfolder. But the images are still uploaded to the wp-content/uploads/ regardless if the "organize" setting is on or off. Should this really effect the wp\_delete\_attachment?
For future reference, if your attachment gets deleted but not your files There is a filter `wp_delete_file`, check if this filter is hooked on somewhere, if it returns `null` your file won't be deleted but the attachment will For me it was due to the WPML plugin, they duplicate attachments and then checks that all the attachments are deleted before actually deleting the file You can either add this action in your theme/plugin, that will delete all translations when using `$force_delete` in `wp_delete_attachment` ``` if ( ! function_exists( 'delete_attachment_translations' ) ) { function delete_attachment_translations( $id ) { remove_action( 'delete_attachment', 'delete_attachment_translations' ); $langs = apply_filters( 'wpml_active_languages', [] ); if ( ! empty( $langs ) ) { global $wp_filter; //We need to temporarly remove WPML's hook or they will cache the result and not delete the file // Sadly they used a filter on a non global class instance, so we cannot access it via regular wp hook $hooks = $wp_filter['wp_delete_file']->callbacks[10]; unset( $wp_filter['wp_delete_file']->callbacks[10] ); foreach ( $langs as $code => $info ) { $post_id = apply_filters( 'wpml_object_id', $id, 'attachment', false, $code ); if ( $id == $post_id ) { continue; } wp_delete_attachment( $post_id, true ); } $wp_filter['wp_delete_file']->callbacks[10] = $hooks; } add_action( 'delete_attachment', 'delete_attachment_translations' ); } add_action( 'delete_attachment', 'delete_attachment_translations' ); } ``` Or check this option in your WPML settings (But it applies to all posts types, not just attachments) [![enter image description here](https://i.stack.imgur.com/hnthm.jpg)](https://i.stack.imgur.com/hnthm.jpg)
181,509
<p>I would like to remove index.php from my permalink. I am using Codeigniter website. I have passed the requirements to use pretty permalink:<BR> <strong>-PHP Version 5.4.27 Codeigniter <BR> -IIS 7.5<BR> -URL Rewrite 2.0<BR> -Server API: FAST CGI<BR></strong></p> <p>Before, I have removed index.php from codeigniter. I wonder if wordpress webconfig file has conflicted with codeigniter. Some help on determining the right webconfig would be greatly appreciated!</p> <pre><code>website.com/en/user =&gt; codeigniter with the controller User website.com/blog /apps /system /blog </code></pre> <p>web config to remove CI index.php</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;rewrite&gt; &lt;rules&gt; &lt;rule name="RuleRemoveIndex" stopProcessing="true"&gt; &lt;match url="^(.*)$" ignoreCase="false" /&gt; &lt;conditions&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" /&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" /&gt; &lt;/conditions&gt; &lt;action type="Rewrite" url="index.php/{R:1}" appendQueryString="true"/&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>/blog => WP app</p> <p>web.config on WP dir</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;rewrite&gt; &lt;rules&gt; &lt;rule name="wordpress" patternSyntax="Wildcard"&gt; &lt;match url="*"/&gt; &lt;conditions&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/&gt; &lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/&gt; &lt;/conditions&gt; &lt;action type="Rewrite" url="index.php"/&gt; &lt;/rule&gt;&lt;/rules&gt; &lt;/rewrite&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>The same question on stackoverflow:</p> <p><a href="https://stackoverflow.com/questions/29074588/wordpress-pretty-permalink-404-error-installed-on-iis-7-5">https://stackoverflow.com/questions/29074588/wordpress-pretty-permalink-404-error-installed-on-iis-7-5</a></p>
[ { "answer_id": 220810, "author": "xyonme", "author_id": 69220, "author_profile": "https://wordpress.stackexchange.com/users/69220", "pm_score": 2, "selected": false, "text": "<p>After struggling for a while in the web.config structure. I found out we need to clear the rule before to add another rule. Just add tag <code>&lt;/clear&gt;</code></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;configuration&gt;\n&lt;system.webServer&gt;\n&lt;rewrite&gt;\n &lt;rules&gt;\n &lt;clear/&gt;\n &lt;rule name=\"wordpress\" patternSyntax=\"Wildcard\"&gt;\n &lt;match url=\"*\"/&gt;\n &lt;conditions&gt;\n &lt;add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" negate=\"true\"/&gt;\n &lt;add input=\"{REQUEST_FILENAME}\" matchType=\"IsDirectory\" negate=\"true\"/&gt;\n &lt;/conditions&gt;\n &lt;action type=\"Rewrite\" url=\"index.php\"/&gt;\n &lt;/rule&gt;\n&lt;/rules&gt;\n&lt;/rewrite&gt;\n&lt;/system.webServer&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 300892, "author": "Siddharth Shukla", "author_id": 141854, "author_profile": "https://wordpress.stackexchange.com/users/141854", "pm_score": 0, "selected": false, "text": "<p>Make web.config put in the root directory.</p>\n\n<p>User code:</p>\n\n<pre><code> &lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n &lt;configuration&gt;\n &lt;system.webServer&gt;\n\n &lt;httpErrors errorMode=\"Detailed\" /&gt;\n &lt;asp scriptErrorSentToBrowser=\"true\"/&gt;\n\n &lt;rewrite&gt;\n &lt;rules&gt;\n &lt;rule name=\"RuleRemoveIndex\" stopProcessing=\"true\"&gt;\n &lt;match url=\"^(.*)$\" ignoreCase=\"false\" /&gt;\n &lt;conditions&gt;\n &lt;add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" ignoreCase=\"false\" negate=\"true\" /&gt;\n &lt;add input=\"{REQUEST_FILENAME}\" matchType=\"IsDirectory\" ignoreCase=\"false\" negate=\"true\" /&gt;\n &lt;/conditions&gt;\n &lt;action type=\"Rewrite\" url=\"index.php/{R:1}\" appendQueryString=\"true\"/&gt;\n &lt;/rule&gt;\n &lt;/rules&gt;\n &lt;/rewrite&gt;\n\n &lt;/system.webServer&gt;\n\n &lt;system.web&gt;\n &lt;customErrors mode=\"Off\"/&gt;\n &lt;compilation debug=\"true\"/&gt;\n &lt;/system.web&gt;\n</code></pre>\n" } ]
2015/03/18
[ "https://wordpress.stackexchange.com/questions/181509", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69220/" ]
I would like to remove index.php from my permalink. I am using Codeigniter website. I have passed the requirements to use pretty permalink: **-PHP Version 5.4.27 Codeigniter -IIS 7.5 -URL Rewrite 2.0 -Server API: FAST CGI** Before, I have removed index.php from codeigniter. I wonder if wordpress webconfig file has conflicted with codeigniter. Some help on determining the right webconfig would be greatly appreciated! ``` website.com/en/user => codeigniter with the controller User website.com/blog /apps /system /blog ``` web config to remove CI index.php ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="RuleRemoveIndex" stopProcessing="true"> <match url="^(.*)$" ignoreCase="false" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" /> </conditions> <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true"/> </rule> </rules> </rewrite> </system.webServer> </configuration> ``` /blog => WP app web.config on WP dir ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="wordpress" patternSyntax="Wildcard"> <match url="*"/> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/> </conditions> <action type="Rewrite" url="index.php"/> </rule></rules> </rewrite> </system.webServer> </configuration> ``` The same question on stackoverflow: <https://stackoverflow.com/questions/29074588/wordpress-pretty-permalink-404-error-installed-on-iis-7-5>
After struggling for a while in the web.config structure. I found out we need to clear the rule before to add another rule. Just add tag `</clear>` ``` <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <clear/> <rule name="wordpress" patternSyntax="Wildcard"> <match url="*"/> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/> </conditions> <action type="Rewrite" url="index.php"/> </rule> </rules> </rewrite> </system.webServer> </configuration> ```
181,529
<p>simple question, how to get all tags of a custom post type by id? post_type=product. </p> <p>i have tried with <a href="http://codex.wordpress.org/Function_Reference/wp_get_post_tags" rel="nofollow">http://codex.wordpress.org/Function_Reference/wp_get_post_tags</a> in my post loop and the print_r returning me nothing.</p> <p>hence i tried this,</p> <pre><code>$term_list = wp_get_post_terms($post-&gt;ID, 'product_tag', array("fields" =&gt; "all")); print_r($term_list); </code></pre> <p>and it's getting me tags in my <code>print_r($term_list);</code> Thanks</p>
[ { "answer_id": 207497, "author": "Ahmad", "author_id": 82951, "author_profile": "https://wordpress.stackexchange.com/users/82951", "pm_score": -1, "selected": false, "text": "<pre><code>global $post;\n$tags = wp_get_post_tags( $post-&gt;ID );\nif ( $tags ) {\n foreach ( $tags as $tag ) {\n $tag_arr .= $tag-&gt;slug . ',';\n }\n $args = array(\n 'tag' =&gt; $tag_arr,\n 'post_per_page' =&gt; 10,\n 'post__not_in' =&gt; array( $post-&gt;ID ),\n 'post_type' =&gt;'post_type_name'\n );\n $related_posts = get_posts( $args );\n if ( $related_posts ) {\n foreach ( $related_posts as $post ) : setup_postdata( $post ); ?&gt;\n &lt;div class=\"swiper-slide\"&gt;\n &lt;a class=\"hover-effect image-holder\" href=\"&lt;?php the_permalink(); ?&gt;\"&gt;\n &lt;?php the_post_thumbnail(); ?&gt;\n &lt;i class=\"icon-circle icon-circle--thin fa fa-arrow-right\"&gt;&amp;shy;&lt;/i&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n &lt;?php endforeach;\n }\n} \nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 236046, "author": "Luis", "author_id": 83500, "author_profile": "https://wordpress.stackexchange.com/users/83500", "pm_score": 1, "selected": false, "text": "<p>Loop approach: usually archive-{custom_post}.php file.</p>\n\n<p><strong>FIRST</strong>:</p>\n\n<p><em>custom_post_plural</em> Stands for a group of custom posts of certain type.</p>\n\n<p>Example of custom_post_plural: <strong>products</strong></p>\n\n<p><em>custom_post_singular</em> Stands for an individual custom post type.</p>\n\n<p>Example of custom_post_singular: <strong>product</strong></p>\n\n<p><strong>SECOND</strong>:</p>\n\n<p>var <strong>$args_custom_post_plural</strong> are the parameters of the WP_Query.</p>\n\n<p>var <strong>$custom_post_plural</strong> is the execution of the query.</p>\n\n<p>I used var <strong>$custom_post_plural_output</strong> to iterate the content of the WP_Object, specifically with the <em>posts</em> term, making the content of it \"array friendly\".</p>\n\n<p>As you can see I partially used Ahmad instructions for a nested iteration.</p>\n\n<pre><code>$args_custom_post_plural=array(\n 'post_type' =&gt; 'custom_post_singular',\n 'post_status' =&gt; 'publish', \n 'posts_per_page' =&gt; -1, \n 'fields' =&gt; 'ids', \n 'order_by' =&gt;'id', \n 'order' =&gt; 'ASC'\n);\n$custom_post_plural = new WP_Query($args_custom_post_plural);\n$custom_post_plural_output = $custom_post_plural-&gt;posts;\nfor ($i=0; $i &lt; count($custom_post_plural_output); $i++) { \n $tags = wp_get_post_tags($custom_post_plural_output[$i]);\n $buffer_tags ='';\n foreach ( $tags as $tag ) {\n $buffer_tags .= $tag-&gt;name . ',';\n }\n}\necho $buffer_tags;\n</code></pre>\n\n<p><strong>FINALLY</strong>:</p>\n\n<p>FYI If you want to use this in a single-{custom_post}.php file, you can use the following code:</p>\n\n<pre><code>$tags = wp_get_post_tags($post-&gt;ID);\nforeach ( $tags as $tag ) {\n $buffer_tags .= $tag-&gt;name . ',';\n}\necho $buffer_tags;\n</code></pre>\n\n<p>Since you must have a linked post in order to display anything.</p>\n\n<p>Happy coding.</p>\n\n<p>PS. \n@cjbj Why in the hell did you erase my edit, it has something wrong or what?\nAwful management here, and very malicious since I can't respond to a comment due to my reputation points amount.</p>\n" }, { "answer_id": 331361, "author": "David Najman", "author_id": 142958, "author_profile": "https://wordpress.stackexchange.com/users/142958", "pm_score": 0, "selected": false, "text": "<p><strong>wp_get_post_tags</strong> works only for posts, not other post types.\nIf you have a look to /wp-includes/post.php you will see it is calling wp_get_post_terms function with $taxonomy set to '<strong>post_tag</strong>':</p>\n\n<pre><code>function wp_get_post_tags( $post_id = 0, $args = array() ) {\n return wp_get_post_terms( $post_id, 'post_tag', $args );\n}\n</code></pre>\n\n<p>For product tags or other taxonomy you could use <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">get_the_terms()</a> instead :</p>\n\n<pre><code>$tags = get_the_terms( $prod_id, 'product_tag' );\n$tags_names = array();\nif ( ! empty( $tags ) ) {\n foreach ( $tags as $tag ) {\n $tags_names[] = $tag-&gt;name;\n }\n}\n</code></pre>\n" }, { "answer_id": 339874, "author": "chandima", "author_id": 137996, "author_profile": "https://wordpress.stackexchange.com/users/137996", "pm_score": 1, "selected": false, "text": "<p>If you need to get tags by post id you could use the followng function. This will work on anywhere since the method is based on database querying.</p>\n\n<pre><code>function sc_tf_get_tags_as_array($post_id){\n global $wpdb;\n $tbl_terms = $wpdb-&gt;prefix . \"terms\";\n $tbl_term_relationships = $wpdb-&gt;prefix . \"term_relationships\";\n\n $sql = \"SELECT name FROM $tbl_terms WHERE term_id in (SELECT term_taxonomy_id FROM $tbl_term_relationships WHERE object_id='$post_id');\";\n $results = $wpdb-&gt;get_results($sql);\n\n if($results){\n foreach($results as $row){\n $tags_list[] = $row-&gt;name;\n }\n }\n\n return $tags_list;\n }\n</code></pre>\n" } ]
2015/03/18
[ "https://wordpress.stackexchange.com/questions/181529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69017/" ]
simple question, how to get all tags of a custom post type by id? post\_type=product. i have tried with <http://codex.wordpress.org/Function_Reference/wp_get_post_tags> in my post loop and the print\_r returning me nothing. hence i tried this, ``` $term_list = wp_get_post_terms($post->ID, 'product_tag', array("fields" => "all")); print_r($term_list); ``` and it's getting me tags in my `print_r($term_list);` Thanks
Loop approach: usually archive-{custom\_post}.php file. **FIRST**: *custom\_post\_plural* Stands for a group of custom posts of certain type. Example of custom\_post\_plural: **products** *custom\_post\_singular* Stands for an individual custom post type. Example of custom\_post\_singular: **product** **SECOND**: var **$args\_custom\_post\_plural** are the parameters of the WP\_Query. var **$custom\_post\_plural** is the execution of the query. I used var **$custom\_post\_plural\_output** to iterate the content of the WP\_Object, specifically with the *posts* term, making the content of it "array friendly". As you can see I partially used Ahmad instructions for a nested iteration. ``` $args_custom_post_plural=array( 'post_type' => 'custom_post_singular', 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'order_by' =>'id', 'order' => 'ASC' ); $custom_post_plural = new WP_Query($args_custom_post_plural); $custom_post_plural_output = $custom_post_plural->posts; for ($i=0; $i < count($custom_post_plural_output); $i++) { $tags = wp_get_post_tags($custom_post_plural_output[$i]); $buffer_tags =''; foreach ( $tags as $tag ) { $buffer_tags .= $tag->name . ','; } } echo $buffer_tags; ``` **FINALLY**: FYI If you want to use this in a single-{custom\_post}.php file, you can use the following code: ``` $tags = wp_get_post_tags($post->ID); foreach ( $tags as $tag ) { $buffer_tags .= $tag->name . ','; } echo $buffer_tags; ``` Since you must have a linked post in order to display anything. Happy coding. PS. @cjbj Why in the hell did you erase my edit, it has something wrong or what? Awful management here, and very malicious since I can't respond to a comment due to my reputation points amount.