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
288,301
<p>I tried many many times, I read many examples but my .htaccess is not working. My domain is: liebeundsprueche.com/ When I go to www.liebeundsprueche.com/ it doesn't redirect me to liebeundsprueche.com/ Here is my .htaccess file:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; DirectoryIndex index.php RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ %{REQUEST_FILENAME} [L] # invalid code - and useless if the ^ and % were joined RewriteCond %{REQUEST_FILENAME} -d RewriteCond %{REQUEST_FILENAME}/index.php -f RewriteRule ^ %{REQUEST_FILENAME}/index.php [L] # invalid code as the second condition can NEVER happen and the Rule is flawed (regex of ^ !!!). RewriteCond %{HTTP_HOST} ^www\.liebeundsprueche\.com$ RewriteRule ^/?$ "http\:\/\/liebeundspruechee\.com\/" [R=301,L] RewriteCond %{REQUEST_FILENAME} -d RewriteCond %{REQUEST_FILENAME}/index.php !-f RewriteRule ^ 404/ [L] # ditto RewriteRule ^(.*[^/]) index.php?var=$1 [QSA,L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Please let me know where is the error?</p>
[ { "answer_id": 288402, "author": "scytale", "author_id": 128374, "author_profile": "https://wordpress.stackexchange.com/users/128374", "pm_score": 1, "selected": false, "text": "<p>Stage and Prod may be on the same server but are they configured for the same version of PHP?</p>\n\n<p>A W...
2017/12/11
[ "https://wordpress.stackexchange.com/questions/288301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133070/" ]
I tried many many times, I read many examples but my .htaccess is not working. My domain is: liebeundsprueche.com/ When I go to www.liebeundsprueche.com/ it doesn't redirect me to liebeundsprueche.com/ Here is my .htaccess file: ``` # BEGIN WordPress <IfModule mod_rewrite.c> DirectoryIndex index.php RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ %{REQUEST_FILENAME} [L] # invalid code - and useless if the ^ and % were joined RewriteCond %{REQUEST_FILENAME} -d RewriteCond %{REQUEST_FILENAME}/index.php -f RewriteRule ^ %{REQUEST_FILENAME}/index.php [L] # invalid code as the second condition can NEVER happen and the Rule is flawed (regex of ^ !!!). RewriteCond %{HTTP_HOST} ^www\.liebeundsprueche\.com$ RewriteRule ^/?$ "http\:\/\/liebeundspruechee\.com\/" [R=301,L] RewriteCond %{REQUEST_FILENAME} -d RewriteCond %{REQUEST_FILENAME}/index.php !-f RewriteRule ^ 404/ [L] # ditto RewriteRule ^(.*[^/]) index.php?var=$1 [QSA,L] </IfModule> # END WordPress ``` Please let me know where is the error?
You can create your own custom error handler and add stack trace to your error log. ``` set_error_handler('wpse_288408_handle_error'); function wpse_288408_handle_error( $errno, $errstr, $errfile, $errline ) { if( $errno === E_USER_NOTICE ) { $message = 'You have an error notice: "%s" in file "%s" at line: "%s".' ; $message = sprintf($message, $errstr, $errfile, $errline); error_log($message); error_log(wpse_288408_generate_stack_trace()); } } // Function from php.net http://php.net/manual/en/function.debug-backtrace.php#112238 function wpse_288408_generate_stack_trace() { $e = new \Exception(); $trace = explode( "\n" , $e->getTraceAsString() ); // reverse array to make steps line up chronologically $trace = array_reverse($trace); array_shift($trace); // remove {main} array_pop($trace); // remove call to this method $length = count($trace); $result = array(); for ($i = 0; $i < $length; $i++) { $result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering } $result = implode("\n", $result); $result = "\n" . $result . "\n"; return $result; } ``` You can check if this is working by adding `trigger_error` somewhere in your code. ``` trigger_error('Annoying notice'); ``` Your error log should output something like that: ``` 2017/01/02 12:00:00 [error] 999#999: *999 FastCGI sent in stderr: "PHP message: You have an error notice: "Annoying notice" in file "/var/www/test/wp-content/plugins/test/test.php" at line: "99". PHP message: 1) /var/www/test/index.php(17): require('/var/www/test/w...') 2) /var/www/test/wp-blog-header.php(13): require_once('/var/www/test/w...') 3) /var/www/test/wp-load.php(37): require_once('/var/www/test/w...') 4) /var/www/test/wp-config.php(93): require_once('/var/www/test/w...') 5) /var/www/test/wp-settings.php(305): include_once('/var/www/test/w...') 6) /var/www/test/wp-content/plugins/test/test.php(99): trigger_error('Annoying notice') 7) [internal function]: wpse_288408_handle_error(1024, 'Annoying notice', '/var/www/test/w...', 99, Array)" while reading response header from upstream, client: 192.168.33.1, server: test.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9070", host: "test.dev" ``` With this kind of message it will be much easier to find out where the problem is.
288,307
<p>In my plugin I'm using </p> <p><code>add_filter('wp_insert_post_data','filter_blog_post_data');</code> </p> <p>for filtering blog data before it gets saved in the database.</p> <p>However this hook makes <code>post-new.php</code> to load latest post's data, like permalink, slug, author.</p> <p><a href="https://i.stack.imgur.com/o1uSq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o1uSq.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/NInrt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NInrt.png" alt="enter image description here"></a></p> <p>How to get rid of this bug? </p> <p><strong>Note:</strong></p> <p>I'm using <code>Wordpress 4.4.13</code>. </p>
[ { "answer_id": 288311, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": 1, "selected": false, "text": "<p>Not sure what must be causing this. Try replicating your entire filter hook with function in this format:</p>\n...
2017/12/11
[ "https://wordpress.stackexchange.com/questions/288307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133017/" ]
In my plugin I'm using `add_filter('wp_insert_post_data','filter_blog_post_data');` for filtering blog data before it gets saved in the database. However this hook makes `post-new.php` to load latest post's data, like permalink, slug, author. [![enter image description here](https://i.stack.imgur.com/o1uSq.png)](https://i.stack.imgur.com/o1uSq.png) [![enter image description here](https://i.stack.imgur.com/NInrt.png)](https://i.stack.imgur.com/NInrt.png) How to get rid of this bug? **Note:** I'm using `Wordpress 4.4.13`.
Not sure what must be causing this. Try replicating your entire filter hook with function in this format: ``` function filter_handler( $data ) { // do something with the post data return $data; } add_filter( 'wp_insert_post_data', 'filter_handler', '10', 1); ``` Let me know if something happens.
288,345
<p>I have a client who wants to display home plans (a custom post type) on their website in 2 differently branded sections, depending on which listing page the post is accessed from. I found this solution from @gmazzap from a few years ago, and it looks promising, but I can't make it work: <a href="https://wordpress.stackexchange.com/questions/130284/multiple-templates-for-custom-post-type">Multiple templates for custom post type</a></p> <p>Specifically, it fails to modify the URL on the alternate listing page: it simply uses the slug specified in the CPT registration: </p> <pre><code>'rewrite' =&gt; array( 'slug' =&gt; 'plan', 'with_front' =&gt; false ), </code></pre> <p>Which means when I click a plan link on 'page_kioskoverview,php' template it displays the post on the standard 'single-plans.php' template rather than the alternate 'single-kioskplans.php' template.</p> <p>Here's what my code looks like:</p> <pre><code>add_action('template_redirect', 'change_plans_plink'); function change_plans_plink() { if (is_page_template('page_kioskoverview.php')) { add_filter( 'post_link', 'plans_query_string', 10, 2 ); } } function plans_query_string( $url, $post ) { if ( $post-&gt;post_type === 'plans' ) { $url = add_query_arg( array('style'=&gt;'alt'), $url ); } return $url; } //designate alternative single template for above alt link add_action('template_include', 'kiosk_plan_single'); function kiosk_plan_single($template) { if( is_singular('plans') ) { $alt = filter_input(INPUT_GET, 'style', FILTER_SANITIZE_STRING); if ( $alt === 'alt' ) $template = 'single-kioskplans.php'; } return $template; } </code></pre> <p>After a few days looking at it (and trying some variations without success), I cannot spot the problem, but I must be missing something.</p>
[ { "answer_id": 288389, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 3, "selected": true, "text": "<p>To display different templates for the same post type I would make 2 different links, check on which link ...
2017/12/11
[ "https://wordpress.stackexchange.com/questions/288345", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30/" ]
I have a client who wants to display home plans (a custom post type) on their website in 2 differently branded sections, depending on which listing page the post is accessed from. I found this solution from @gmazzap from a few years ago, and it looks promising, but I can't make it work: [Multiple templates for custom post type](https://wordpress.stackexchange.com/questions/130284/multiple-templates-for-custom-post-type) Specifically, it fails to modify the URL on the alternate listing page: it simply uses the slug specified in the CPT registration: ``` 'rewrite' => array( 'slug' => 'plan', 'with_front' => false ), ``` Which means when I click a plan link on 'page\_kioskoverview,php' template it displays the post on the standard 'single-plans.php' template rather than the alternate 'single-kioskplans.php' template. Here's what my code looks like: ``` add_action('template_redirect', 'change_plans_plink'); function change_plans_plink() { if (is_page_template('page_kioskoverview.php')) { add_filter( 'post_link', 'plans_query_string', 10, 2 ); } } function plans_query_string( $url, $post ) { if ( $post->post_type === 'plans' ) { $url = add_query_arg( array('style'=>'alt'), $url ); } return $url; } //designate alternative single template for above alt link add_action('template_include', 'kiosk_plan_single'); function kiosk_plan_single($template) { if( is_singular('plans') ) { $alt = filter_input(INPUT_GET, 'style', FILTER_SANITIZE_STRING); if ( $alt === 'alt' ) $template = 'single-kioskplans.php'; } return $template; } ``` After a few days looking at it (and trying some variations without success), I cannot spot the problem, but I must be missing something.
To display different templates for the same post type I would make 2 different links, check on which link I'm currently on and decide which template to load. Working example: ``` /** * Register event post type * * Registering event post type will add such a permalink structure event/([^/]+)/?$ */ function wpse_288345_register_event_post_type() { $labels = array( 'name' => __( 'Events' ), 'singular_name' => __( 'Event' ), 'add_new' => __( 'Add new' ), 'add_new_item' => __( 'Add new' ), 'edit_item' => __( 'Edit' ), 'new_item' => __( 'New' ), 'view_item' => __( 'View' ), 'search_items' => __( 'Search' ), 'not_found' => __( 'Not found' ), 'not_found_in_trash' => __( 'Not found Events in trash' ), 'parent_item_colon' => __( 'Parent' ), 'menu_name' => __( 'Events' ), ); $args = array( 'labels' => $labels, 'hierarchical' => false, 'supports' => array( 'title', 'page-attributes' ), 'taxonomies' => array(), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => false, 'publicly_queryable' => true, 'exclude_from_search' => false, 'has_archive' => true, 'query_var' => true, 'can_export' => true, 'rewrite' => array('slug' => 'event'), 'capability_type' => 'post', ); register_post_type( 'event', $args ); } add_action( 'init', 'wpse_288345_register_event_post_type' ); /** * Add custom rewrite rule for event post type. * * Remember to flush rewrite rules to apply changes. */ function wpse_288345_add_event_rewrite_rules() { /** * Custom rewrite rules for one post type. * * We wil know on which url we are by $_GET parameters 'performers' and 'summary'. Which we will add to * public query vars to obtain them in convinient way. */ add_rewrite_rule('event/performers/([^/]+)/?$', 'index.php?post_type=event&name=$matches[1]&performers=1', 'top'); add_rewrite_rule('event/summary/([^/]+)/?$', 'index.php?post_type=event&name=$matches[1]&summary=1', 'top'); } add_action('init', 'wpse_288345_add_event_rewrite_rules'); /** * Add 'performers' and 'summary' custom event query vars. */ function wpse_288345_register_event_query_vars( $vars ) { $vars[] = 'performers'; $vars[] = 'summary'; return $vars; } add_filter( 'query_vars', 'wpse_288345_register_event_query_vars' ); /** * Decide which template to load */ function wpse_288345_load_performers_or_summary_template( $template ) { // Get public query vars $performers = (int) get_query_var( 'performers', 0 ); $summary = (int) get_query_var( 'summary', 0 ); // If performer = 1 then we are on event/performers link if( $performers === 1 ) { $template = locate_template( array( 'single-event-performers.php' ) ); } // If summary = 1 then we are on event/summary link if( $summary === 1 ) { $template = locate_template( array( 'single-event-summary.php' ) ); } if($template == '') { throw new \Exception('No template found'); } return $template; } add_filter( 'template_include', 'wpse_288345_load_performers_or_summary_template' ); ```
288,363
<p>I am receiving this notice when trying to use the $wpdb->prepare function:</p> <blockquote> <p>Notice: wpdb::prepare was called <strong>incorrectly</strong>. The query does not contain the correct number of placeholders (7) for the number of arguments passed (4). Please see Debugging in WordPress for more information. (This message was added in version 4.8.3.) in C:\wamp\www\wpml\wp-includes\functions.php on line 4139</p> </blockquote> <p>I looked at other posts on this topic and I don't see any of the same problems from those threads in my code. When developing this notice greatly slows down my application so I want to find a solution.</p> <pre><code>function get_meta_range($meta_key) { global $wpdb; // $meta_key = '_price' $include = '7275,7266,7256,7237,7196,7192,7164'; $min = floor( $wpdb-&gt;get_var( $wpdb-&gt;prepare(' SELECT min(meta_value + 0) FROM %1$s LEFT JOIN %2$s ON %1$s.ID = %2$s.post_id WHERE ( meta_key =\'%3$s\' OR meta_key =\'%4$s\' ) AND meta_value != "" AND ( %1$s.ID IN (' . $include . ') )' , $wpdb-&gt;posts, $wpdb-&gt;postmeta, $meta_key, '_min_variation' . $meta_key ) ) ); // $min = 15 } </code></pre>
[ { "answer_id": 288365, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>The <code>wpdb::prepare</code> says that you should not quote placeholders, yet in your code there is:</p>\n...
2017/12/12
[ "https://wordpress.stackexchange.com/questions/288363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58254/" ]
I am receiving this notice when trying to use the $wpdb->prepare function: > > Notice: wpdb::prepare was called **incorrectly**. The > query does not contain the correct number of placeholders (7) for the > number of arguments passed (4). Please see Debugging in > WordPress for more information. (This message was added in version > 4.8.3.) in C:\wamp\www\wpml\wp-includes\functions.php on line 4139 > > > I looked at other posts on this topic and I don't see any of the same problems from those threads in my code. When developing this notice greatly slows down my application so I want to find a solution. ``` function get_meta_range($meta_key) { global $wpdb; // $meta_key = '_price' $include = '7275,7266,7256,7237,7196,7192,7164'; $min = floor( $wpdb->get_var( $wpdb->prepare(' SELECT min(meta_value + 0) FROM %1$s LEFT JOIN %2$s ON %1$s.ID = %2$s.post_id WHERE ( meta_key =\'%3$s\' OR meta_key =\'%4$s\' ) AND meta_value != "" AND ( %1$s.ID IN (' . $include . ') )' , $wpdb->posts, $wpdb->postmeta, $meta_key, '_min_variation' . $meta_key ) ) ); // $min = 15 } ```
Numbered placeholders don't work as you'd expect, and are going to be removed altogether at some point in the future, so should be considered invalid syntax. So with this in mind, the error describes the problem- your query has 7 placeholders, but you only pass 4 values. For the repeated values, you just need to repeat them where you pass the substitutions.
288,381
<p>I need to remove description textarea from a custom taxonomy edit screen in admin.</p> <p>I'm actually doing this with the following jQuery line</p> <pre><code>$('.form-field.term-description-wrap').remove(); </code></pre> <p>but I would like doing it in PHP. Is it possible?</p> <p>I'm looking at the <strong>{$taxonomy}_edit_form_fields</strong> hook. Is this the right one? If so which lines of code should I add into the callback function?</p>
[ { "answer_id": 288382, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>It's not possible, there's no hook. The hook you mentioned is an <em>action</em>, not a filter, and can...
2017/12/12
[ "https://wordpress.stackexchange.com/questions/288381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85556/" ]
I need to remove description textarea from a custom taxonomy edit screen in admin. I'm actually doing this with the following jQuery line ``` $('.form-field.term-description-wrap').remove(); ``` but I would like doing it in PHP. Is it possible? I'm looking at the **{$taxonomy}\_edit\_form\_fields** hook. Is this the right one? If so which lines of code should I add into the callback function?
check out [this thread](https://wordpress.stackexchange.com/questions/56569/remove-the-category-taxonomy-description-field) - I'm afraid nothing has changed since then, there is still no way of filtering the description field (it's just html hardcoded in the file <https://github.com/WordPress/WordPress/blob/master/wp-admin/edit-tags.php#L484>, so you can't remove it with php without editing the core files, which is **never** a right way to go). The hook you're using, `{$taxonomy}_edit_form_fields` is fired on single term edit screen before the standard fields are printed, so you can use it to add something more, but not for filtering standard fields. I'd say you need to hold on to your JS solution for now or even better - go with CSS `display: none;` solution to make sure the field doesn't show up when JavaScript is disabled and to avoid flickering, like mentioned [here](https://wordpress.stackexchange.com/questions/56569/remove-the-category-taxonomy-description-field/182652#182652).
288,391
<p>So I was asked to add some analytics code to a sponsored post. I usually do it like this:</p> <pre><code>if(is_single('post_slug')): // Insert analytics code; endif; </code></pre> <p>However, I cannot figure out how to do it on a post with a custom post type.</p> <p>I found this function which takes the slug of the custom post type:</p> <p>is_singular('event');</p> <p>My question is, is there a function that would take the custom post type and the slug of the post?</p> <p>Would really appreciate your help. Thanks!</p>
[ { "answer_id": 288398, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 1, "selected": false, "text": "<p>You can mix two functions:</p>\n\n<pre><code>if( is_singular( $post_type ) &amp;&amp; is_single( $post_sl...
2017/12/12
[ "https://wordpress.stackexchange.com/questions/288391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133129/" ]
So I was asked to add some analytics code to a sponsored post. I usually do it like this: ``` if(is_single('post_slug')): // Insert analytics code; endif; ``` However, I cannot figure out how to do it on a post with a custom post type. I found this function which takes the slug of the custom post type: is\_singular('event'); My question is, is there a function that would take the custom post type and the slug of the post? Would really appreciate your help. Thanks!
You can mix two functions: ``` if( is_singular( $post_type ) && is_single( $post_slug ) ): // Insert analytics code; endif; ```
288,407
<p>I added post_meta 'batch' to 'assignment' custom post as follows:</p> <pre><code>update_post_meta( $id, 'batch', strip_tags($_POST['batch'])); </code></pre> <p>Now I am trying to retrieve this data as follows:</p> <pre><code>$args = array( 'post_type' =&gt; 'assignment', 'post_status' =&gt; 'publish', ); $assignments = new WP_Query( $args ); </code></pre> <p>I want to get all data having 'batch=2017'. How can I do this? </p>
[ { "answer_id": 288398, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 1, "selected": false, "text": "<p>You can mix two functions:</p>\n\n<pre><code>if( is_singular( $post_type ) &amp;&amp; is_single( $post_sl...
2017/12/12
[ "https://wordpress.stackexchange.com/questions/288407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120824/" ]
I added post\_meta 'batch' to 'assignment' custom post as follows: ``` update_post_meta( $id, 'batch', strip_tags($_POST['batch'])); ``` Now I am trying to retrieve this data as follows: ``` $args = array( 'post_type' => 'assignment', 'post_status' => 'publish', ); $assignments = new WP_Query( $args ); ``` I want to get all data having 'batch=2017'. How can I do this?
You can mix two functions: ``` if( is_singular( $post_type ) && is_single( $post_slug ) ): // Insert analytics code; endif; ```
288,416
<p>How do I retrieve the IDs of unattached media in my post?</p> <p>I have two posts: <strong>POST A</strong> and <strong>POST B</strong> and a PDF file called <strong>file.pdf</strong>.</p> <p>I've uploaded <strong>file.pdf</strong> to <strong>POST A</strong> but then also inserted it in <strong>POST B</strong>.</p> <p>Now the <strong>file.pdf</strong> is still attached to <strong>POST A</strong> so I'm not able to get it's ID by using <code>get_attached_media( '', $post_B_id )</code>. </p> <p>How can i retrieve the list of all media used in <strong>POST B</strong>, including files such as my file.pdf - not attached, by inserted into <strong>POST B</strong>?</p>
[ { "answer_id": 288421, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 0, "selected": false, "text": "<p>it is not easy to get an short hint, source code to find all usages of an media file. WordPress creates an relati...
2017/12/12
[ "https://wordpress.stackexchange.com/questions/288416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101988/" ]
How do I retrieve the IDs of unattached media in my post? I have two posts: **POST A** and **POST B** and a PDF file called **file.pdf**. I've uploaded **file.pdf** to **POST A** but then also inserted it in **POST B**. Now the **file.pdf** is still attached to **POST A** so I'm not able to get it's ID by using `get_attached_media( '', $post_B_id )`. How can i retrieve the list of all media used in **POST B**, including files such as my file.pdf - not attached, by inserted into **POST B**?
Yes you can do this! Is it simple/easy? Sort of... Is it fast and scalable? Oh dear god no . The Super Expensive Solution ---------------------------- The solution here is this function: ``` $post_id = url_to_postid( $url ); ``` The problem is that this is a very slow function that's expensive to call. If you call this when displaying every post, your DB server will be under super high strain and may fall over unless you configure it correctly and put it on a dedicated machine. ***Note:*** you can't call this function early, it has to be on the `setup_theme` hook or later, or it'll cause a fatal error to occur. With this function, we can pull out every URL in the posts content, and do a test to see if it begins with the URL of our site. If it does, we can check to see if it matches any of the attachments, and if it doesn't, then we know it's unattached and can use this function to grab a copy. How to retrieve all the URLs in a posts content is a topic or another question however. Testing if a URL is for an attached attachment is a simple if statement comparison in a loop ( foreach attached thing, check if its URL matches the URL we're testing ) Speeding Things Up ------------------ There are a few things that might mitigate the cost of this function: * Run the process on the save and update posts hook and store the result in post meta * Wrap the function in a caching layer to speed things up ( only effective if there's an object caching solution in place such as memcached, not as effective as the previous mechanism ) -Use a less precise method written by Pippins plugins that uses a DB query. This will bypass caches and it's still expensive, but not as expensive as `url_to_postid`. It also only works with GUIDs, hence the accuracy trade off An Even More Expensive Solution ------------------------------- Query all the attachments via `WP_Query` and load all of them into memory, then check each attachment 1 by 1 to see if they appear in your post. This is by far the slowest and most expensive way to do this: * As you upload more media, you have to load more when doing the query, for any site with more than 30 or 40 attachments you're going to get out of memory fatal errors * It's a heavy database operation, your DB has to send all of the attachments, and if you've got several people browsing at once, this will get very problematic * It will never scale past 5-10 concurrent users, and that's if you're lucky * It's slow, checking every attachment takes time
288,434
<p>When I embed a Youtube video onto my page, is there a way to change the thumbnail displayed (<a href="https://imgur.com/F4daH3U" rel="nofollow noreferrer">screenshot</a>)? I do not have admin access to the Youtube video in-question.</p> <p>I would prefer a non-plugin solution if possible. I found <a href="http://wpdecoder.com/video-tutorials/custom-thumbnail-with-youtube-video/" rel="nofollow noreferrer">these instructions</a>, but they did not work.</p>
[ { "answer_id": 288436, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 3, "selected": true, "text": "<p>The <a href=\"https://codex.wordpress.org/Video_Shortcode\" rel=\"nofollow noreferrer\"><code>[video...
2017/12/12
[ "https://wordpress.stackexchange.com/questions/288434", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
When I embed a Youtube video onto my page, is there a way to change the thumbnail displayed ([screenshot](https://imgur.com/F4daH3U))? I do not have admin access to the Youtube video in-question. I would prefer a non-plugin solution if possible. I found [these instructions](http://wpdecoder.com/video-tutorials/custom-thumbnail-with-youtube-video/), but they did not work.
The [`[video]` shortcode](https://codex.wordpress.org/Video_Shortcode) can be used with the `src` being an URL of a youtube video. To set a placeholder, preview thumbnail use `poster`, it even works nicely via GUI. In the end it should look somewhat like the bellow example. ``` [video src="https://www.youtube.com/watch?v=XYZ" poster="http://example.com/wp-content/uploads/2017/01/example.jpg"] ```
288,463
<p>I asked a question yesterday, but I realised that the code was not correct and it was my bad, so I refactored everything. I have a form with two fields which when user submits and takes a quiz test, gets registered and his scores saved to user meta data table. My user gets created, but when I want to add extra meta data of quiz scores for him using <code>update_user_meta</code> it just doesn't do anything. Here is my code:</p> <pre><code> if (isset($_POST['submit_contact'])) { $email = $_POST['email_contact']; $full = $_POST['fullname_contact']; $_SESSION["email"] = $email; $_SESSION["name"] = $full; echo $_SESSION["mail"]; } function save_quiz_score() { $score = $_POST['score']; $email = $_SESSION["email"]; $username = $_SESSION["name"]; $user = get_user_by("email", $email); register_new_user($email, $_SESSION["email"]); update_user_meta($user, "quiz_scores", $score); echo $_SESSION["mail"]; } </code></pre> <p>I'm using <code>session_start</code> and echo the sessions out and can see the emails, so that is no problem. <code>$_POST['score']</code> is also valid, because in the past I tried saving it on its own and it worked fine, so neither is that a problem. I just feel like I tried everything and feel like giving up. Maybe an extra pair of eyes can help me and notice a problem. Thanks in advance.</p>
[ { "answer_id": 288464, "author": "Limpuls", "author_id": 133005, "author_profile": "https://wordpress.stackexchange.com/users/133005", "pm_score": 2, "selected": false, "text": "<p>Solved the problem by changing these lines:</p>\n\n<pre><code>register_new_user($email, $_SESSION[\"email\"...
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288463", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133005/" ]
I asked a question yesterday, but I realised that the code was not correct and it was my bad, so I refactored everything. I have a form with two fields which when user submits and takes a quiz test, gets registered and his scores saved to user meta data table. My user gets created, but when I want to add extra meta data of quiz scores for him using `update_user_meta` it just doesn't do anything. Here is my code: ``` if (isset($_POST['submit_contact'])) { $email = $_POST['email_contact']; $full = $_POST['fullname_contact']; $_SESSION["email"] = $email; $_SESSION["name"] = $full; echo $_SESSION["mail"]; } function save_quiz_score() { $score = $_POST['score']; $email = $_SESSION["email"]; $username = $_SESSION["name"]; $user = get_user_by("email", $email); register_new_user($email, $_SESSION["email"]); update_user_meta($user, "quiz_scores", $score); echo $_SESSION["mail"]; } ``` I'm using `session_start` and echo the sessions out and can see the emails, so that is no problem. `$_POST['score']` is also valid, because in the past I tried saving it on its own and it worked fine, so neither is that a problem. I just feel like I tried everything and feel like giving up. Maybe an extra pair of eyes can help me and notice a problem. Thanks in advance.
You set the variable `$user` before you created this user.. It should be like this and you need to check if the user already exists ``` $user = get_user_by("email", $email); // Its return you the user object if($user) { update_user_meta($user->ID, "quiz_scores", $score); } else { $user_id = register_new_user($email, $_SESSION["email"]); update_user_meta($user_id, "quiz_scores", $score); } ```
288,486
<p>I want to display 4 column footer menu. but when I add new menu the wp_nav_menu create a &lt; li > and add every menu items to it.</p> <p><a href="https://i.stack.imgur.com/Fw6do.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fw6do.png" alt="enter image description here"></a></p> <p>now, how can I wrap every li element with a custom div tag with a class?</p> <p>I need this output :</p> <p><a href="https://i.stack.imgur.com/zQrnB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zQrnB.png" alt="enter image description here"></a></p> <p>In the above image, you can see every menu is wrapped inside a div. </p> <p>I tried with wp_nav_menu() it does not help. As I'm new to WordPress theme development I don't know more option.</p> <p>Is there any way I can say WordPress to add a div element with a custom class to add before every menu item?</p> <p>Thanks :)</p>
[ { "answer_id": 288464, "author": "Limpuls", "author_id": 133005, "author_profile": "https://wordpress.stackexchange.com/users/133005", "pm_score": 2, "selected": false, "text": "<p>Solved the problem by changing these lines:</p>\n\n<pre><code>register_new_user($email, $_SESSION[\"email\"...
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288486", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133193/" ]
I want to display 4 column footer menu. but when I add new menu the wp\_nav\_menu create a < li > and add every menu items to it. [![enter image description here](https://i.stack.imgur.com/Fw6do.png)](https://i.stack.imgur.com/Fw6do.png) now, how can I wrap every li element with a custom div tag with a class? I need this output : [![enter image description here](https://i.stack.imgur.com/zQrnB.png)](https://i.stack.imgur.com/zQrnB.png) In the above image, you can see every menu is wrapped inside a div. I tried with wp\_nav\_menu() it does not help. As I'm new to WordPress theme development I don't know more option. Is there any way I can say WordPress to add a div element with a custom class to add before every menu item? Thanks :)
You set the variable `$user` before you created this user.. It should be like this and you need to check if the user already exists ``` $user = get_user_by("email", $email); // Its return you the user object if($user) { update_user_meta($user->ID, "quiz_scores", $score); } else { $user_id = register_new_user($email, $_SESSION["email"]); update_user_meta($user_id, "quiz_scores", $score); } ```
288,496
<p>I want to force all user to access https (SSL) entire website. I tried to set it at options-general.php page,I try to install a plug-in. They are all success.But I can't enter or access all wp-admin page either. The website will redirect to myaccount page when force to SSL is on.</p> <p>how can i access admin page with ssl? what did i miss?</p>
[ { "answer_id": 288464, "author": "Limpuls", "author_id": 133005, "author_profile": "https://wordpress.stackexchange.com/users/133005", "pm_score": 2, "selected": false, "text": "<p>Solved the problem by changing these lines:</p>\n\n<pre><code>register_new_user($email, $_SESSION[\"email\"...
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133200/" ]
I want to force all user to access https (SSL) entire website. I tried to set it at options-general.php page,I try to install a plug-in. They are all success.But I can't enter or access all wp-admin page either. The website will redirect to myaccount page when force to SSL is on. how can i access admin page with ssl? what did i miss?
You set the variable `$user` before you created this user.. It should be like this and you need to check if the user already exists ``` $user = get_user_by("email", $email); // Its return you the user object if($user) { update_user_meta($user->ID, "quiz_scores", $score); } else { $user_id = register_new_user($email, $_SESSION["email"]); update_user_meta($user_id, "quiz_scores", $score); } ```
288,504
<p>Is it possible to rewrite this kind of action url on all the posts of a custom post type?</p> <p><strong>Original url:</strong></p> <pre><code>example.com/custompostype/post-title/?action=play-123 </code></pre> <p>(Desired Output) <strong>Rewriting to:</strong></p> <pre><code>example.com/custompostype/post-title/play-123 </code></pre> <p>123 = <strong>postid</strong></p> <p>Is it possible to do it with wordpress's functions instead of direct .htaccess edit?</p>
[ { "answer_id": 288505, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": -1, "selected": false, "text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\"....
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288504", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133205/" ]
Is it possible to rewrite this kind of action url on all the posts of a custom post type? **Original url:** ``` example.com/custompostype/post-title/?action=play-123 ``` (Desired Output) **Rewriting to:** ``` example.com/custompostype/post-title/play-123 ``` 123 = **postid** Is it possible to do it with wordpress's functions instead of direct .htaccess edit?
I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint) ``` add_action('init', 'wpse42279_add_endpoints'); function wpse42279_add_endpoints() { add_rewrite_endpoint('play', EP_PERMALINK); } ``` And then i used this conditionals on the single page: ``` global $post; $pid = $post->ID; $var = get_query_var( 'play' ); if( !empty($var) and $var == $pid) : // do stuff endif; ``` **Now here's the working pretty link:** ``` example.com/custompostype/post-title/play/123/ ``` **Instead of:** example.com/custompostype/post-title/?play=123 However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: ``` example.com/?custompostype=321 ``` (It redirects to the pretty link: example.com/custompostype/post-title/)
288,530
<p>All in <em>single.php</em> file in <em>Genesis child theme</em>.</p> <p>I have an <code>echo</code> of <code>divs</code> and in between I in one of the <code>anchors</code> I am trying to insert author's post url via a <code>variable</code>, like so:</p> <pre><code>function my_function() { $author = get_the_author_meta( $post-&gt;post_author ); $author_link = get_author_posts_url($author); $author_avatar = get_avatar_url(get_the_author_meta( $post-&gt;post_author )); $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'full' ); //.. echo '&lt;div&gt; // .. &lt;div class=""&gt; By &lt;a href="'.$author_link.'"&gt;Author&lt;/a&gt; &lt;/div&gt;' &lt;/div&gt; } genesis(); </code></pre> <p>I have tried: <code>the_author_posts_url();</code>, <code>get_the_author_meta('user_url');</code>, <code>get_author_posts_url();</code>, <code>get_author_posts_url( get_the_author_meta( 'ID' ) );</code> every time the link is either empty or it generates </p> <pre><code>http://localhost/author </code></pre> <p>without outputting the specific author.</p> <p>full code of single.php is here:</p> <p> <p>function custom_entry_content() { $author = get_the_author_meta( $post->post_author );</p> <pre><code>$author_link = get_author_posts_url($author); $author_avatar = get_avatar_url(get_the_author_meta( $post-&gt;post_author )); $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'full' ); echo '&lt;div style="margin-bottom: 50px;position: relative; text-align:center; width:100%;background-image: url('.$featured_image[0].'); height: 502px; background-size: cover; background-repeat: no-repeat;"&gt; &lt;div class="post-title-box"&gt; &lt;h1 class="the-title"&gt; '. get_the_title(). '&lt;/h1&gt; &lt;/div&gt; &lt;div class="post-auth-info"&gt; &lt;div class="vertical-middle" style="display:inline-block"&gt; &lt;div class=""&gt; By &lt;a href="'.$author_link.'"&gt;Author&lt;/a&gt; &lt;/div&gt; &lt;time class="mk-publish-date" datetime="2017-11-01"&gt; &lt;a href="#"&gt;Published ' . time_elapsed_string(get_the_date()). '&lt;/a&gt; &lt;/time&gt; &lt;/div&gt; &lt;div style="display:inline-block"&gt; &lt;a href="'.$author_link.'"&gt; &lt;div&gt; &lt;img alt="" src="'.$author_avatar.'" class="img-circle avatar avatar-55 " height="55" width="55" style="height:55px;width:55px"&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;'; } // Removes Published by and time data from before the post content area remove_action( 'genesis_entry_header', 'genesis_post_info', 12); add_filter( 'genesis_attr_site-inner', 'remove_top_padding'); function remove_top_padding( $attributes ) { $attributes['class'] = 'container box nopadding'; return $attributes; } // Adds left padding to content add_filter( 'genesis_attr_content', 'padding_left'); function padding_left( $attributes ) { if ( 'full-width-content' === genesis_site_layout() ) $attributes['class'] = ''; else $attributes['class'] = 'col-md-8 single-post-entry'; return $attributes; } genesis(); </code></pre> <p>Many thanks in advance!</p>
[ { "answer_id": 288505, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": -1, "selected": false, "text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\"....
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103078/" ]
All in *single.php* file in *Genesis child theme*. I have an `echo` of `divs` and in between I in one of the `anchors` I am trying to insert author's post url via a `variable`, like so: ``` function my_function() { $author = get_the_author_meta( $post->post_author ); $author_link = get_author_posts_url($author); $author_avatar = get_avatar_url(get_the_author_meta( $post->post_author )); $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); //.. echo '<div> // .. <div class=""> By <a href="'.$author_link.'">Author</a> </div>' </div> } genesis(); ``` I have tried: `the_author_posts_url();`, `get_the_author_meta('user_url');`, `get_author_posts_url();`, `get_author_posts_url( get_the_author_meta( 'ID' ) );` every time the link is either empty or it generates ``` http://localhost/author ``` without outputting the specific author. full code of single.php is here: function custom\_entry\_content() { $author = get\_the\_author\_meta( $post->post\_author ); ``` $author_link = get_author_posts_url($author); $author_avatar = get_avatar_url(get_the_author_meta( $post->post_author )); $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); echo '<div style="margin-bottom: 50px;position: relative; text-align:center; width:100%;background-image: url('.$featured_image[0].'); height: 502px; background-size: cover; background-repeat: no-repeat;"> <div class="post-title-box"> <h1 class="the-title"> '. get_the_title(). '</h1> </div> <div class="post-auth-info"> <div class="vertical-middle" style="display:inline-block"> <div class=""> By <a href="'.$author_link.'">Author</a> </div> <time class="mk-publish-date" datetime="2017-11-01"> <a href="#">Published ' . time_elapsed_string(get_the_date()). '</a> </time> </div> <div style="display:inline-block"> <a href="'.$author_link.'"> <div> <img alt="" src="'.$author_avatar.'" class="img-circle avatar avatar-55 " height="55" width="55" style="height:55px;width:55px"> </div> </a> </div> </div> </div>'; } // Removes Published by and time data from before the post content area remove_action( 'genesis_entry_header', 'genesis_post_info', 12); add_filter( 'genesis_attr_site-inner', 'remove_top_padding'); function remove_top_padding( $attributes ) { $attributes['class'] = 'container box nopadding'; return $attributes; } // Adds left padding to content add_filter( 'genesis_attr_content', 'padding_left'); function padding_left( $attributes ) { if ( 'full-width-content' === genesis_site_layout() ) $attributes['class'] = ''; else $attributes['class'] = 'col-md-8 single-post-entry'; return $attributes; } genesis(); ``` Many thanks in advance!
I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint) ``` add_action('init', 'wpse42279_add_endpoints'); function wpse42279_add_endpoints() { add_rewrite_endpoint('play', EP_PERMALINK); } ``` And then i used this conditionals on the single page: ``` global $post; $pid = $post->ID; $var = get_query_var( 'play' ); if( !empty($var) and $var == $pid) : // do stuff endif; ``` **Now here's the working pretty link:** ``` example.com/custompostype/post-title/play/123/ ``` **Instead of:** example.com/custompostype/post-title/?play=123 However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: ``` example.com/?custompostype=321 ``` (It redirects to the pretty link: example.com/custompostype/post-title/)
288,538
<p>The problem is simple, the solution doesn't want to meet me. I want to display (echo) the percentage of the VAT I have defined in my woocommerce settings. Let's say it is 24%. I want to echo it (in the cart or checkout page somewhere, it doesn't really matter) as 0.24 . If I change the VAT to 22%, then automatically it should show 0.22 and so on... How can I achieve this? Many thanks in advance</p>
[ { "answer_id": 288505, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": -1, "selected": false, "text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\"....
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288538", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80225/" ]
The problem is simple, the solution doesn't want to meet me. I want to display (echo) the percentage of the VAT I have defined in my woocommerce settings. Let's say it is 24%. I want to echo it (in the cart or checkout page somewhere, it doesn't really matter) as 0.24 . If I change the VAT to 22%, then automatically it should show 0.22 and so on... How can I achieve this? Many thanks in advance
I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint) ``` add_action('init', 'wpse42279_add_endpoints'); function wpse42279_add_endpoints() { add_rewrite_endpoint('play', EP_PERMALINK); } ``` And then i used this conditionals on the single page: ``` global $post; $pid = $post->ID; $var = get_query_var( 'play' ); if( !empty($var) and $var == $pid) : // do stuff endif; ``` **Now here's the working pretty link:** ``` example.com/custompostype/post-title/play/123/ ``` **Instead of:** example.com/custompostype/post-title/?play=123 However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: ``` example.com/?custompostype=321 ``` (It redirects to the pretty link: example.com/custompostype/post-title/)
288,540
<p>I am creating a membership site where I am trying to login a particular user from a link sent to their email address.</p> <p>I have a custom post typed called "Members", where I have stored a unique key with the name "user_key". After a particular process, the email is sent to that user with an auto login link.</p> <p>An example link looks like the following</p> <p><a href="http://example.com/process/?key=DcP2K7cmBUrLVRjizs78RAuuoMGRFc6F6TMDm6E6" rel="nofollow noreferrer">http://example.com/process/?key=DcP2K7cmBUrLVRjizs78RAuuoMGRFc6F6TMDm6E6</a></p> <p>Process is the page which handles the login part. Here is the code used in that page.</p> <pre><code>get_header(); $key = $_GET['key']; $args = array( 'post_type' =&gt; 'member', 'meta_value' =&gt; $key ); $properties = new WP_Query($args); if($properties-&gt;have_posts()) : while($properties-&gt;have_posts()) : $properties-&gt;the_post(); $author = $post-&gt;post_author; $user = get_user_by('ID', $author); $user_id = $user-&gt;ID; echo $user_id; wp_set_current_user($user_id, $loginusername); wp_set_auth_cookie($user_id); do_action('wp_login', $loginusername); wp_redirect( home_url() ); endwhile; endif; wp_reset_query(); get_footer(); </code></pre> <p>When I go to that particular link, I get the following error.</p> <p>"Warning: Cannot modify header information - headers already sent"</p> <p>From what I understand, I think it's the "wp_set_auth_cookie" part which is done after the headers are loaded, which is creating that problem.</p> <p>Anyone has any ideas how to fix it?</p>
[ { "answer_id": 288505, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": -1, "selected": false, "text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\"....
2017/12/13
[ "https://wordpress.stackexchange.com/questions/288540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30753/" ]
I am creating a membership site where I am trying to login a particular user from a link sent to their email address. I have a custom post typed called "Members", where I have stored a unique key with the name "user\_key". After a particular process, the email is sent to that user with an auto login link. An example link looks like the following <http://example.com/process/?key=DcP2K7cmBUrLVRjizs78RAuuoMGRFc6F6TMDm6E6> Process is the page which handles the login part. Here is the code used in that page. ``` get_header(); $key = $_GET['key']; $args = array( 'post_type' => 'member', 'meta_value' => $key ); $properties = new WP_Query($args); if($properties->have_posts()) : while($properties->have_posts()) : $properties->the_post(); $author = $post->post_author; $user = get_user_by('ID', $author); $user_id = $user->ID; echo $user_id; wp_set_current_user($user_id, $loginusername); wp_set_auth_cookie($user_id); do_action('wp_login', $loginusername); wp_redirect( home_url() ); endwhile; endif; wp_reset_query(); get_footer(); ``` When I go to that particular link, I get the following error. "Warning: Cannot modify header information - headers already sent" From what I understand, I think it's the "wp\_set\_auth\_cookie" part which is done after the headers are loaded, which is creating that problem. Anyone has any ideas how to fix it?
I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint) ``` add_action('init', 'wpse42279_add_endpoints'); function wpse42279_add_endpoints() { add_rewrite_endpoint('play', EP_PERMALINK); } ``` And then i used this conditionals on the single page: ``` global $post; $pid = $post->ID; $var = get_query_var( 'play' ); if( !empty($var) and $var == $pid) : // do stuff endif; ``` **Now here's the working pretty link:** ``` example.com/custompostype/post-title/play/123/ ``` **Instead of:** example.com/custompostype/post-title/?play=123 However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: ``` example.com/?custompostype=321 ``` (It redirects to the pretty link: example.com/custompostype/post-title/)
288,564
<p>I need to include jquery in a single page template of my theme. But it looks like it doesn't want to.</p> <p>I tried calling it with wp_enqueue_scripts() but i does nothing. Here is what is in functions.php</p> <pre><code>add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' ); function custom_theme_load_scripts() { wp_enqueue_script( 'jquery' ); } </code></pre> <p>And what I'm trying to do in page-template.php</p> <pre><code>&lt;?php custom_theme_load_scripts(); ?&gt; &lt;script type="text/javascript"&gt; //stuff using jquery here &lt;/script&gt; </code></pre> <p>Even calling it before the header doesn't work.</p> <p>I don't want to load an external jquery file since wordpress already have one, but I'm banging my head against the wall as I have no idea why it doesn't work.</p> <p>Any ideas ?</p>
[ { "answer_id": 288572, "author": "dipak_pusti", "author_id": 44528, "author_profile": "https://wordpress.stackexchange.com/users/44528", "pm_score": 0, "selected": false, "text": "<p>What you are trying to do in <code>page-template.php</code> is totally wrong. Try to run conditional quer...
2017/12/14
[ "https://wordpress.stackexchange.com/questions/288564", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132140/" ]
I need to include jquery in a single page template of my theme. But it looks like it doesn't want to. I tried calling it with wp\_enqueue\_scripts() but i does nothing. Here is what is in functions.php ``` add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' ); function custom_theme_load_scripts() { wp_enqueue_script( 'jquery' ); } ``` And what I'm trying to do in page-template.php ``` <?php custom_theme_load_scripts(); ?> <script type="text/javascript"> //stuff using jquery here </script> ``` Even calling it before the header doesn't work. I don't want to load an external jquery file since wordpress already have one, but I'm banging my head against the wall as I have no idea why it doesn't work. Any ideas ?
Okay, this is awkward but I resolved my own issue. jQuery was indeed charging but... I was using `$this`. And as someone already said on another thread: > > By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries). > > > So, you must use `jquery` as a selector instead of `$`. Hope it can help someone else ! Thanks a everyone trying to help !
288,581
<p>Issue URL - <a href="http://www.creativescripters.com/clients/testwp/uncategorized/image-resized/" rel="nofollow noreferrer">http://www.creativescripters.com/clients/testwp/uncategorized/image-resized/</a></p> <p>I am using wordpress (self hosted) latest version, The problem is I am looking to get a thumbnail from the resized/scaled image, and when I do that wordpress returns the test-150x150.jpg i.e. Thumbnail from the original image and not the resized image which should have been test-e1513229707262-150x150.jpg</p> <p>Step to reproduce the issue </p> <ol> <li>Upload an image , Scale it (click edit on uploaded image and change width and click scale). Wordpress will rename the image and add an Suffix Id to the name so you can confirm the image have been scaled. for eg if you uploaded test.jpg after scaling image name will become test-randomstring.jpg</li> </ol> <p><a href="https://i.stack.imgur.com/TTIaG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TTIaG.png" alt="enter image description here"></a></p> <ol start="2"> <li><p>When I call get_the_post_thumbnail($post, 'full') I get the correct image The resized one i.e. test-randomstring.jpg <a href="https://i.stack.imgur.com/T3vPE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T3vPE.png" alt="enter image description here"></a></p></li> <li><p>When I try to get a different size of the scaled image for eg I need thumbnail generated from the image size and I call function get_the_post_thumbnail($post, 'thumbnail') wordpress return the THUMBNAIL from actual image (the one I uploaded initially test.jpg and not the resized one test-randomstring.jpg)</p></li> </ol> <p>Screenshot - <a href="https://i.imgur.com/sQKoZcF.png" rel="nofollow noreferrer">https://i.imgur.com/sQKoZcF.png</a></p>
[ { "answer_id": 288584, "author": "Tarang koradiya", "author_id": 128666, "author_profile": "https://wordpress.stackexchange.com/users/128666", "pm_score": 2, "selected": false, "text": "<p>Used img tag and display image</p>\n\n<pre><code>&lt;img src=\"&lt;?= $img_url=get_the_post_thumbna...
2017/12/14
[ "https://wordpress.stackexchange.com/questions/288581", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10639/" ]
Issue URL - <http://www.creativescripters.com/clients/testwp/uncategorized/image-resized/> I am using wordpress (self hosted) latest version, The problem is I am looking to get a thumbnail from the resized/scaled image, and when I do that wordpress returns the test-150x150.jpg i.e. Thumbnail from the original image and not the resized image which should have been test-e1513229707262-150x150.jpg Step to reproduce the issue 1. Upload an image , Scale it (click edit on uploaded image and change width and click scale). Wordpress will rename the image and add an Suffix Id to the name so you can confirm the image have been scaled. for eg if you uploaded test.jpg after scaling image name will become test-randomstring.jpg [![enter image description here](https://i.stack.imgur.com/TTIaG.png)](https://i.stack.imgur.com/TTIaG.png) 2. When I call get\_the\_post\_thumbnail($post, 'full') I get the correct image The resized one i.e. test-randomstring.jpg [![enter image description here](https://i.stack.imgur.com/T3vPE.png)](https://i.stack.imgur.com/T3vPE.png) 3. When I try to get a different size of the scaled image for eg I need thumbnail generated from the image size and I call function get\_the\_post\_thumbnail($post, 'thumbnail') wordpress return the THUMBNAIL from actual image (the one I uploaded initially test.jpg and not the resized one test-randomstring.jpg) Screenshot - <https://i.imgur.com/sQKoZcF.png>
Used img tag and display image ``` <img src="<?= $img_url=get_the_post_thumbnail_url($post->ID,'full'); ?>" alt="image" /> ```
288,595
<p>I'm trying to create some custom REST API endpoints which get products with some special conditions, for example, one endpoint for featured products. I tried to use the <code>wc_get_products</code> function like this:</p> <pre><code>add_action('rest_api_init', 'my_custom_featured_product_endpoint'); function my_custom_featured_product_endpoint() { register_rest_route('custom-endpoints/v1', '/products/featured', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'my_custom_featured_product_callback', )); } function my_custom_featured_product_callback() { $meta_query = WC()-&gt;query-&gt;get_meta_query(); $tax_query = WC()-&gt;query-&gt;get_tax_query(); $tax_query[] = array( 'taxonomy' =&gt; 'product_visibility', 'field' =&gt; 'name', 'terms' =&gt; 'featured', 'operator' =&gt; 'IN', ); $args = array( 'tax_query' =&gt; $tax_query, 'meta_query' =&gt; $meta_query, ); $result = wc_get_products($args); return rest_ensure_response($result); } </code></pre> <p>The result is just some empty arrays. I can get those products with old fashion <code>get_posts</code> to replace <code>wc_get_products</code> but the output format doesn't have some properties like 'price', 'images' ...</p> <p>So are there any alternatives for <code>wc_get_products</code> to use for custom REST API endpoints or are there any ways to make it work?</p> <p>P/S: I tested the query by change the callback function like so:</p> <pre><code>function my_custom_featured_product_callback() { $result = wc_get_product(99);//Yes there is a product with ID 99 return rest_ensure_response($result); } </code></pre> <p>The result stays the same, just an empty array. So I think the issue must lie with the <code>wc_get_products</code> and <code>wc_get_product</code> functions. Maybe the <code>rest_api_init</code> is not the proper hook for those functions?</p>
[ { "answer_id": 307143, "author": "Brauperle", "author_id": 145985, "author_profile": "https://wordpress.stackexchange.com/users/145985", "pm_score": 0, "selected": false, "text": "<p>I faced a similar behavior where <code>$wc_get_product</code> always returned empty objects from a custom...
2017/12/14
[ "https://wordpress.stackexchange.com/questions/288595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133259/" ]
I'm trying to create some custom REST API endpoints which get products with some special conditions, for example, one endpoint for featured products. I tried to use the `wc_get_products` function like this: ``` add_action('rest_api_init', 'my_custom_featured_product_endpoint'); function my_custom_featured_product_endpoint() { register_rest_route('custom-endpoints/v1', '/products/featured', array( 'methods' => 'GET', 'callback' => 'my_custom_featured_product_callback', )); } function my_custom_featured_product_callback() { $meta_query = WC()->query->get_meta_query(); $tax_query = WC()->query->get_tax_query(); $tax_query[] = array( 'taxonomy' => 'product_visibility', 'field' => 'name', 'terms' => 'featured', 'operator' => 'IN', ); $args = array( 'tax_query' => $tax_query, 'meta_query' => $meta_query, ); $result = wc_get_products($args); return rest_ensure_response($result); } ``` The result is just some empty arrays. I can get those products with old fashion `get_posts` to replace `wc_get_products` but the output format doesn't have some properties like 'price', 'images' ... So are there any alternatives for `wc_get_products` to use for custom REST API endpoints or are there any ways to make it work? P/S: I tested the query by change the callback function like so: ``` function my_custom_featured_product_callback() { $result = wc_get_product(99);//Yes there is a product with ID 99 return rest_ensure_response($result); } ``` The result stays the same, just an empty array. So I think the issue must lie with the `wc_get_products` and `wc_get_product` functions. Maybe the `rest_api_init` is not the proper hook for those functions?
you missed something, when you get a product using wc\_get\_product it returns to you an abstract object, so if you need to get product do this ``` $product = wc_get_product($product_id); return $product->get_data(); ``` also you can use all the other functionalities too, such as: ``` $product->get_status(); $product->get_gallery_image_ids(); ... ```
288,650
<p>I have a front-end form posting to admin_post. Here, I do some validation. If there are errors, I want to show an error message for the relevant fields.</p> <p>However, I don't know how to redirect back to the submission page and retain the field values.</p> <p>Currently I'm using the below:.</p> <pre><code>add_action( 'admin_post_form', 'form_post' ); function form_post() { $validate = // Validation functions go here if ($validate == 'error') { $url = wp_get_referer(); $url = add_query_arg( 'error', 'email', $url ); wp_redirect( $url ); die(); } } </code></pre> <p>But this (naturally) doesn't retain the filled form field values, so the user has to start all over again.</p> <p>If I were posting to the same page as the form this would be simple - just set the value as <code>&lt;input value="&lt;?php echo $_POST['email']; ?&gt;"&gt;</code> but I'm not sure how to achieve the same effect using admin-post.</p> <p>Can you help?</p>
[ { "answer_id": 295462, "author": "Kevin Robinson", "author_id": 133315, "author_profile": "https://wordpress.stackexchange.com/users/133315", "pm_score": 0, "selected": false, "text": "<p>I solved this using the $_SESSION variable to pass data to the following page.</p>\n\n<pre><code> i...
2017/12/14
[ "https://wordpress.stackexchange.com/questions/288650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133315/" ]
I have a front-end form posting to admin\_post. Here, I do some validation. If there are errors, I want to show an error message for the relevant fields. However, I don't know how to redirect back to the submission page and retain the field values. Currently I'm using the below:. ``` add_action( 'admin_post_form', 'form_post' ); function form_post() { $validate = // Validation functions go here if ($validate == 'error') { $url = wp_get_referer(); $url = add_query_arg( 'error', 'email', $url ); wp_redirect( $url ); die(); } } ``` But this (naturally) doesn't retain the filled form field values, so the user has to start all over again. If I were posting to the same page as the form this would be simple - just set the value as `<input value="<?php echo $_POST['email']; ?>">` but I'm not sure how to achieve the same effect using admin-post. Can you help?
You can use `set_transient` with the `user_id` if you are relying on users being logged in, otherwise, cookie would probably be better. For logged in users, you can have the `user_id` get set within the name of the transient. An example here: ``` function form_post() { $user_info = wp_get_current_user(); $user_id = $user_info->exists() && !empty($user_info->ID) ? $user_info->ID : 0; $url = wp_get_referer(); // Validate the form fields and populate this array when errors occur $validation_errors = array(); // I like to use the id of the elements as keys and the error string as the values of the array, so i can add error class to the elements if needed easily... // Now to save the transient... if (!empty($validation_errors)) { set_transient('validation_errors_' . $user_id, $my_errors); wp_redirect($url); die(); } } ``` Now before you output your form element on your page, you just need to check the transient for that user, if exists, output the errors, than delete the transient right after that... For example: ``` <?php $user_info = wp_get_current_user(); $user_id = $user_info->exists() && !empty($user_info->ID) ? $user_info->ID : 0; $validation_errors = get_transient('validation_errors_' . $user_id); if ($validation_errors !== FALSE) { echo '<div class="errors">Please fix the following Validation Errors:<ul><li>' . implode('</li><li>', $validation_errors) . '</li></ul></div>'; delete_transient('validation_errors_' . $user_id); } ?> <form ...> </form> ```
288,655
<p>On my search.php page, I have a "Sort By" dropdown that almost works exactly how I want it to --</p> <pre><code>&lt;select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;"&gt; &lt;option disabled&gt;Sort by&lt;/option&gt; &lt;option value="&amp;orderby=date&amp;order=dsc"&gt;Newest&lt;/option&gt; &lt;option value="&amp;orderby=date&amp;order=asc"&gt;Oldest&lt;/option&gt; &lt;/select&gt; &lt;script type="text/javascript"&gt; &lt;?php if (( $_GET['orderby'] == 'date') &amp;&amp; ( $_GET['order'] == 'dsc')) { ?&gt; document.getElementById('sortbox').value='orderby=date&amp;order=dsc'; &lt;?php } elseif (( $_GET['orderby'] == 'date') &amp;&amp; ( $_GET['order'] == 'asc')) { ?&gt; document.getElementById('sortbox').value='orderby=date&amp;order=asc'; &lt;?php } else { ?&gt; document.getElementById('sortbox').value='orderby=date&amp;order=desc'; &lt;?php } ?&gt; &lt;/script&gt; </code></pre> <p>When Im on the search results page, the sort dropdown will sort the current results according to date by grabbing the url and appending to it then reloading the page with the results ---</p> <pre><code>// Before mydomain.com/?s=Search&amp;property_city=new-york-city&amp;beds=Any // After mydomain.com/?s=Search&amp;property_city=new-york-city&amp;beds=Any&amp;orderby=date&amp;order=dsc </code></pre> <p>However, I am now trying to improve the code further by using it to sort based on numeric custom fields (high to low and low to high).</p> <p>It seems all the info I can find on the subject have much more complicated ways of doing so. Is there anyway of doing this using the code I already started on?</p> <p><strong>UPDATE</strong></p> <p>I seem to be getting closer -</p> <p>On my search.php page I have this before my loop ----</p> <pre><code>&lt;select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;"&gt; &lt;option disabled&gt;Sort by&lt;/option&gt; &lt;option value="&amp;orderby=date&amp;order=dsc"&gt;Newest&lt;/option&gt; &lt;option value="&amp;orderby=date&amp;order=asc"&gt;Oldest&lt;/option&gt; &lt;option value="&amp;orderby=property_price&amp;order=asc"&gt;Most Expensive&lt;/option&gt; &lt;option value="&amp;orderby=property_price&amp;order=dsc"&gt;Least Expensive&lt;/option&gt; &lt;option value="&amp;orderby=property_area&amp;order=dsc"&gt;Largest&lt;/option&gt; &lt;option value="&amp;orderby=property_area&amp;order=asc"&gt;Smallest&lt;/option&gt; &lt;/select&gt; &lt;script type="text/javascript"&gt; &lt;?php if (( $_GET['orderby'] == 'date') &amp;&amp; ( $_GET['order'] == 'dsc')) { ?&gt; document.getElementById('sortbox').value='orderby=date&amp;order=dsc'; &lt;?php } elseif (( $_GET['orderby'] == 'date') &amp;&amp; ( $_GET['order'] == 'asc')) { ?&gt; document.getElementById('sortbox').value='orderby=date&amp;order=asc'; &lt;?php } elseif (( $_GET['orderby'] == 'property_price') &amp;&amp; ( $_GET['order'] == 'asc')) { ?&gt; document.getElementById('sortbox').value='orderby=property_price&amp;order=asc'; &lt;?php } elseif (( $_GET['orderby'] == 'property_price') &amp;&amp; ( $_GET['order'] == 'dsc')) { ?&gt; document.getElementById('sortbox').value='orderby=property_price&amp;order=dsc'; &lt;?php } elseif (( $_GET['orderby'] == 'property_area') &amp;&amp; ( $_GET['order'] == 'asc')) { ?&gt; document.getElementById('sortbox').value='orderby=property_area&amp;order=asc'; &lt;?php } elseif (( $_GET['orderby'] == 'property_area') &amp;&amp; ( $_GET['order'] == 'dsc')) { ?&gt; document.getElementById('sortbox').value='orderby=property_area&amp;order=dsc'; &lt;?php } else { ?&gt; document.getElementById('sortbox').value='orderby=date&amp;order=desc'; &lt;?php } ?&gt; &lt;/script&gt; </code></pre> <p>where it says "orderby=xxx" I just use my names for my custom fields.</p>
[ { "answer_id": 289693, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 1, "selected": false, "text": "<p><code>orderby</code> should be e.g. <code>meta_value</code> or <code>meta_value_num</code> – variou...
2017/12/14
[ "https://wordpress.stackexchange.com/questions/288655", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
On my search.php page, I have a "Sort By" dropdown that almost works exactly how I want it to -- ``` <select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;"> <option disabled>Sort by</option> <option value="&orderby=date&order=dsc">Newest</option> <option value="&orderby=date&order=asc">Oldest</option> </select> <script type="text/javascript"> <?php if (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'dsc')) { ?> document.getElementById('sortbox').value='orderby=date&order=dsc'; <?php } elseif (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'asc')) { ?> document.getElementById('sortbox').value='orderby=date&order=asc'; <?php } else { ?> document.getElementById('sortbox').value='orderby=date&order=desc'; <?php } ?> </script> ``` When Im on the search results page, the sort dropdown will sort the current results according to date by grabbing the url and appending to it then reloading the page with the results --- ``` // Before mydomain.com/?s=Search&property_city=new-york-city&beds=Any // After mydomain.com/?s=Search&property_city=new-york-city&beds=Any&orderby=date&order=dsc ``` However, I am now trying to improve the code further by using it to sort based on numeric custom fields (high to low and low to high). It seems all the info I can find on the subject have much more complicated ways of doing so. Is there anyway of doing this using the code I already started on? **UPDATE** I seem to be getting closer - On my search.php page I have this before my loop ---- ``` <select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;"> <option disabled>Sort by</option> <option value="&orderby=date&order=dsc">Newest</option> <option value="&orderby=date&order=asc">Oldest</option> <option value="&orderby=property_price&order=asc">Most Expensive</option> <option value="&orderby=property_price&order=dsc">Least Expensive</option> <option value="&orderby=property_area&order=dsc">Largest</option> <option value="&orderby=property_area&order=asc">Smallest</option> </select> <script type="text/javascript"> <?php if (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'dsc')) { ?> document.getElementById('sortbox').value='orderby=date&order=dsc'; <?php } elseif (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'asc')) { ?> document.getElementById('sortbox').value='orderby=date&order=asc'; <?php } elseif (( $_GET['orderby'] == 'property_price') && ( $_GET['order'] == 'asc')) { ?> document.getElementById('sortbox').value='orderby=property_price&order=asc'; <?php } elseif (( $_GET['orderby'] == 'property_price') && ( $_GET['order'] == 'dsc')) { ?> document.getElementById('sortbox').value='orderby=property_price&order=dsc'; <?php } elseif (( $_GET['orderby'] == 'property_area') && ( $_GET['order'] == 'asc')) { ?> document.getElementById('sortbox').value='orderby=property_area&order=asc'; <?php } elseif (( $_GET['orderby'] == 'property_area') && ( $_GET['order'] == 'dsc')) { ?> document.getElementById('sortbox').value='orderby=property_area&order=dsc'; <?php } else { ?> document.getElementById('sortbox').value='orderby=date&order=desc'; <?php } ?> </script> ``` where it says "orderby=xxx" I just use my names for my custom fields.
Ok I got it figured out using @Nicolai suggestion and also a answer from another question (which I seem to have lost the link to). For starters, I had to make sure my numbers have no commas in it which I had already done by saving my post meta without it. Then the code I found in another question, I used and placed into my **functions.php** file -- ``` function wpse139657_orderby(){ if( isset($_GET['orderby']) ){ $order = $_GET['order'] or 'DESC'; set_query_var('orderby', 'meta_value_num'); //set_query_var('meta_type', 'numeric'); set_query_var('meta_key', $_GET['orderby']); set_query_var('order', $order); } } add_filter('pre_get_posts','wpse139657_orderby'); ``` Then on my **search.php** page I used the following code for the select dropdown -- ``` <select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;"> <option disabled>Sort by</option> <option value="&orderby=date&order=dsc">Newest</option> <option value="&orderby=date&order=asc">Oldest</option> <option value="&orderby=property_price2&order=DESC">Most Expensive</option> <option value="&orderby=property_price2&order=ASC">Least Expensive</option> <option value="&orderby=area2&order=DESC">Largest</option> <option value="&orderby=area2&order=ASC">Smallest</option> </select> ``` This seems to do the trick and works with pagination, only issues I have right now is -- > > 1. Ugly Urls > 2. When the page is reloaded with the posts sorted, the dropdown select goes back to default ie "Newest" when it should still be on the > option the user chose. > > >
288,740
<p>In my addon, I would like to check on activation, if a column of a specific table in the DB already exists to avoid to implement it for each activation.</p> <p>Something like this :</p> <pre><code>class MainClassAddon{ public function __construct(){ register_activation_hook( __FILE__, array( $this, 'install' ) ); } public function install(){ if( /*Checking if column c in table wp_t exists*/ ){ $wpdb-&gt;query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1"); } } } new MainClassAddon(); register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) ); </code></pre>
[ { "answer_id": 288741, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": 2, "selected": true, "text": "<p>I found this solution : <a href=\"https://stackoverflow.com/questions/21330932/add-new-column-to-wordpress-...
2017/12/15
[ "https://wordpress.stackexchange.com/questions/288740", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
In my addon, I would like to check on activation, if a column of a specific table in the DB already exists to avoid to implement it for each activation. Something like this : ``` class MainClassAddon{ public function __construct(){ register_activation_hook( __FILE__, array( $this, 'install' ) ); } public function install(){ if( /*Checking if column c in table wp_t exists*/ ){ $wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1"); } } } new MainClassAddon(); register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) ); ```
I found this solution : [here](https://stackoverflow.com/questions/21330932/add-new-column-to-wordpress-database#answer-21331762) So... ``` class MainClassAddon{ public function __construct(){ register_activation_hook( __FILE__, array( $this, 'install' ) ); } public function install(){ $row = $wpdb->get_results( "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'wp_t' AND column_name = 'c'" ); if(empty($row)){ $wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1"); } } } new MainClassAddon(); register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) ); ```
288,769
<p>My client explicitly does not want to use 'multisite' wordpress option. <br> My client has a main site and 199 sub sites (other domains). <br> A user has usermeta with meta key: branch_id <br></p> <p>As an example (completely made up names): <br> Main site: kero.com <br> Sub site: uka.com (and many others) <br></p> <p>Both domains have SSL certificates.</p> <p>The end goal is as following: When you log in to the main site (kero.com). I have build a plugin which checks which branch ID is attached to the user. It goes like this:</p> <pre><code>function myplugin_auth_signon( $username, $password ) { $user = get_user_by('email', $username); $user_id = $user-&gt;ID; $key = 'branch_id'; $single = true; $branch = get_user_meta( $user_id, $key, $single ); if($branch == 'number') { //magic happens here! $cookie = "cookie.txt"; $postdata = "log=" . $username . "&amp;pwd=" . $password . "&amp;wp-submit=Log%20In&amp;redirect_to=" . $url . "wp-admin/&amp;testcookie=1"; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url . "wp-login.php"); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0); curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt ($ch, CURLOPT_REFERER, $url . "wp-login.php"); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); curl_close($ch); //This is from the answer of the link. On the end url the users get redirected from wp-admin to my-account header('location: ' . $url . 'wp-admin/'); die(); //after logging in redirect the user to uka.com/my-account } add_action( 'wp_authenticate', 'myplugin_auth_signon', 30, 2 ); </code></pre> <p>So I build all kind of stuff, I used this link on the //magic happens here: <a href="https://stackoverflow.com/questions/728274/php-curl-post-to-login-to-wordpress">Click here.</a></p> <p>It does not work as intented. It keeps me on the main website, but when I click on 'store' it is in the sub site. When I go to my-account (where I should be logged in) i'm not logged in anymore.</p> <p>I wrote some other code:</p> <pre><code>$response = wp_remote_post( $url, array( 'method' =&gt; 'POST', 'timeout' =&gt; 45, 'redirection' =&gt; 5, 'httpversion' =&gt; '1.0', 'blocking' =&gt; true, 'headers' =&gt; array(), 'body' =&gt; array( 'username' =&gt; $username, 'password' =&gt; $password ), 'cookies' =&gt; array() ) ); </code></pre> <p>I don't really know how to use this for my personal goal. I can echo the results, but then get a big array of headers etc. And when I surf to the subsite: I'm not logged in... So it just does not keep sessions/cookies.</p> <p>TBH: I'm really a beginner on the whole session/cookie/security stuff. Most of the time I build in Wordpress or Laravel and most of the security stuff is already handled then.</p> <p>Thanks everyone who is taking the time to read this.</p> <p><strong>UPDATE: Added extra cUrl code!</strong></p>
[ { "answer_id": 288808, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You can not set cookies form site A that will be applicable on site B, therefor your \"login by proxy\" s...
2017/12/16
[ "https://wordpress.stackexchange.com/questions/288769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131414/" ]
My client explicitly does not want to use 'multisite' wordpress option. My client has a main site and 199 sub sites (other domains). A user has usermeta with meta key: branch\_id As an example (completely made up names): Main site: kero.com Sub site: uka.com (and many others) Both domains have SSL certificates. The end goal is as following: When you log in to the main site (kero.com). I have build a plugin which checks which branch ID is attached to the user. It goes like this: ``` function myplugin_auth_signon( $username, $password ) { $user = get_user_by('email', $username); $user_id = $user->ID; $key = 'branch_id'; $single = true; $branch = get_user_meta( $user_id, $key, $single ); if($branch == 'number') { //magic happens here! $cookie = "cookie.txt"; $postdata = "log=" . $username . "&pwd=" . $password . "&wp-submit=Log%20In&redirect_to=" . $url . "wp-admin/&testcookie=1"; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url . "wp-login.php"); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0); curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt ($ch, CURLOPT_REFERER, $url . "wp-login.php"); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); curl_close($ch); //This is from the answer of the link. On the end url the users get redirected from wp-admin to my-account header('location: ' . $url . 'wp-admin/'); die(); //after logging in redirect the user to uka.com/my-account } add_action( 'wp_authenticate', 'myplugin_auth_signon', 30, 2 ); ``` So I build all kind of stuff, I used this link on the //magic happens here: [Click here.](https://stackoverflow.com/questions/728274/php-curl-post-to-login-to-wordpress) It does not work as intented. It keeps me on the main website, but when I click on 'store' it is in the sub site. When I go to my-account (where I should be logged in) i'm not logged in anymore. I wrote some other code: ``` $response = wp_remote_post( $url, array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => array( 'username' => $username, 'password' => $password ), 'cookies' => array() ) ); ``` I don't really know how to use this for my personal goal. I can echo the results, but then get a big array of headers etc. And when I surf to the subsite: I'm not logged in... So it just does not keep sessions/cookies. TBH: I'm really a beginner on the whole session/cookie/security stuff. Most of the time I build in Wordpress or Laravel and most of the security stuff is already handled then. Thanks everyone who is taking the time to read this. **UPDATE: Added extra cUrl code!**
For future reference I am answering my own question. Disclaimer: This was a freelance gig and had to be done in a X time frame. Which mean that this was the quickest AND simplest option. What I did was: 1. Installed the plugin <https://wordpress.org/plugins/user-session-synchronizer/> - Give this guy some credit, this plugin is insanely good. Besides the insane fact that it's FREE... 2. I hooked in on the wp\_loaded hook and checked what branch ID the user had; The plugin I wrote had options with branch ID's and the urls. It So after checking what branch ID the user had: it checked which url corresponded with the branch ID. Then echo'd ``` echo "<script>setTimeout(function() { parent.self.location='https://server.com'; }, 1500);</script>"; ```
288,776
<p>This is my array of image URL's added to the same custom field named images.</p> <pre><code> $images = get_post_custom_values( 'images' ); </code></pre> <p>I need to print all these images in a template file.</p>
[ { "answer_id": 288780, "author": "Cyclonecode", "author_id": 14870, "author_profile": "https://wordpress.stackexchange.com/users/14870", "pm_score": 2, "selected": false, "text": "<p>Since you are storing an url for each image you can create a query to get the id of the attachment based ...
2017/12/16
[ "https://wordpress.stackexchange.com/questions/288776", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104464/" ]
This is my array of image URL's added to the same custom field named images. ``` $images = get_post_custom_values( 'images' ); ``` I need to print all these images in a template file.
This is how i ended up coding the solution : ``` $images = get_post_custom_values( 'images' ); if ( $images ) { echo '<div class="image-wrap">'; if ( $image_header ) { echo '<div class="header">' . esc_html( $image_header ) . '</div>'; } foreach ( (array) $images as $image ) { $url = esc_url( $image ); $alt = esc_html( the_title_attribute( 'echo=0' ) ); if ( $url ) { echo '<img class="image-section" src="' . $url . '" alt="' . $alt . '" />'; } } echo '</div>'; } ``` **To get the i.d from a URL** You can use [attachment\_url\_to\_postid](https://developer.wordpress.org/reference/functions/attachment_url_to_postid/) like this : ``` $url = 'http://example.com/img.png'; $id = attachment_url_to_postid( $url ); $alt = get_post_meta( $id, '_wp_attachment_image_alt', true ); ```
288,781
<p>I am trying to debug a plugin and am using <code>error_log()</code> in various places to see what various things are. I am using the following:</p> <pre><code>error_log( print_r( $variable ) ); </code></pre> <p>When I look at <code>debug.log</code>, all I see is <code>1</code> and the actual output of the <code>error_log()</code> function is sent to the browser instead.</p> <p>I know another plugin is not doing this as all are disabled with the exception of the one I am writing. In my <code>wp-config.php</code>, I have defined <code>WP_DEBUG_DISPLAY</code> as <code>false</code>.</p> <p>The same thing happens if I use <code>var_dump()</code> and <code>var_export()</code>. Other functions like <code>gettype()</code> work just fine.</p> <p>Is there any way to get the output into <code>debug.log</code>?</p>
[ { "answer_id": 288782, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 5, "selected": true, "text": "<p>The <a href=\"http://php.net/manual/en/function.print-r.php\" rel=\"noreferrer\">print_r</a> function accept sec...
2017/12/16
[ "https://wordpress.stackexchange.com/questions/288781", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80069/" ]
I am trying to debug a plugin and am using `error_log()` in various places to see what various things are. I am using the following: ``` error_log( print_r( $variable ) ); ``` When I look at `debug.log`, all I see is `1` and the actual output of the `error_log()` function is sent to the browser instead. I know another plugin is not doing this as all are disabled with the exception of the one I am writing. In my `wp-config.php`, I have defined `WP_DEBUG_DISPLAY` as `false`. The same thing happens if I use `var_dump()` and `var_export()`. Other functions like `gettype()` work just fine. Is there any way to get the output into `debug.log`?
The [print\_r](http://php.net/manual/en/function.print-r.php) function accept second parameter for `return` so it retrun the variable instead of printing it. ``` print_r($expression, $return) ``` So you can do ``` error_log( print_r( $variable, true ) ); ```
288,793
<p>I making homepage in the local host.</p> <p>I need <code>wp_query</code> with Ajax.</p> <p>but there's some error. I don't know why. Can you help me?</p> <p>----> this is <code>load_more_ajax.js</code></p> <pre><code>var page = 2; var date_pass = "&lt;?php echo($date_filter);?&gt;"; var compare_pass = "&lt;?php echo($compare);?&gt;"; var ajaxurl = "&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;"; jQuery(function($){ $('body').on('click', '.loadmore', function(){ var data = { 'action': 'rnm_load_more_ajax', 'page': page, 'date_filter': date_pass, 'compare': compare_pass, 'security': '&lt;?php echo wp_create_nonce("load_more_posts"); ?&gt;' }; $.post(ajaxurl, data, function(response){ $('.race-posts').append(response); page++; }); }); }); </code></pre> <p>and, this is <code>load_more_ajax.php</code></p> <pre><code>&lt;?php function load_posts_by_ajax_callback(){ echo ("hello"); } </code></pre> <p>this is add_action</p> <pre><code>add_action('wp_ajax_rnm_load_more_ajax', 'load_posts_by_ajax_callback'); add_action('wp_ajax_nopriv_rnm_load_more_ajax', 'load_posts_by_ajax_callback'); add_action('wp_enqueue_scripts', 'rnm_enqueue_fn'); function rnm_enqueue_fn(){ wp_register_script('rnm_load_more', get_template_directory_uri() .'/js/load_more_ajax.js', array(), false, true); wp_enqueue_script('rnm_load_more'); } </code></pre> <p>This makes error like this. <a href="https://i.stack.imgur.com/2emED.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2emED.jpg" alt="error message"></a></p> <p>I think there's some problem in the url of 'admin-ajax.php'</p> <p>But I can't find any solution. </p>
[ { "answer_id": 288795, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 0, "selected": false, "text": "<p>You can't use PHP code in a .js file, unless you change your config. Even if you did, you'd also have to load ...
2017/12/17
[ "https://wordpress.stackexchange.com/questions/288793", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133185/" ]
I making homepage in the local host. I need `wp_query` with Ajax. but there's some error. I don't know why. Can you help me? ----> this is `load_more_ajax.js` ``` var page = 2; var date_pass = "<?php echo($date_filter);?>"; var compare_pass = "<?php echo($compare);?>"; var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; jQuery(function($){ $('body').on('click', '.loadmore', function(){ var data = { 'action': 'rnm_load_more_ajax', 'page': page, 'date_filter': date_pass, 'compare': compare_pass, 'security': '<?php echo wp_create_nonce("load_more_posts"); ?>' }; $.post(ajaxurl, data, function(response){ $('.race-posts').append(response); page++; }); }); }); ``` and, this is `load_more_ajax.php` ``` <?php function load_posts_by_ajax_callback(){ echo ("hello"); } ``` this is add\_action ``` add_action('wp_ajax_rnm_load_more_ajax', 'load_posts_by_ajax_callback'); add_action('wp_ajax_nopriv_rnm_load_more_ajax', 'load_posts_by_ajax_callback'); add_action('wp_enqueue_scripts', 'rnm_enqueue_fn'); function rnm_enqueue_fn(){ wp_register_script('rnm_load_more', get_template_directory_uri() .'/js/load_more_ajax.js', array(), false, true); wp_enqueue_script('rnm_load_more'); } ``` This makes error like this. [![error message](https://i.stack.imgur.com/2emED.jpg)](https://i.stack.imgur.com/2emED.jpg) I think there's some problem in the url of 'admin-ajax.php' But I can't find any solution.
You need to pass the values to the localization script, *"right"* after this line: ``` wp_enqueue_script('rnm_load_more'); ``` I'm going to pass the admin URL to your script by using [`wp_localize_script`](https://codex.wordpress.org/Function_Reference/wp_localize_script): ``` $localization = array( 'ajax_url' => admin_url('admin-ajax.php'), ); wp_localize_script( 'rnm_load_more', 'jjang', $localization ); ``` Now, you can use the `ajax_url` in your script: ``` var ajaxurl = rnm_load_more.ajax_url; ``` You can send the rest of the data by using this method.
288,804
<p>I have a custom function in functions.php that excludes specific category from the category list:</p> <pre><code>function incomplete_cat_list() { $first_time = 1; foreach((get_the_category()) as $category) { if ($category-&gt;cat_name != 'Category Name') { if ($first_time == 1) { echo '&lt;a class="cat-list" href="' . get_category_link( $category-&gt;term_id ) . '" title="' . sprintf( __( "See all %s" ), $category-&gt;name ) . '" ' . '&gt;' . $category-&gt;name.'&lt;/a&gt;'; $first_time = 0; } else { } } } } </code></pre> <p>I would like to use it in related posts foreach loop, but I'm not sure how to do it... Here's the code for displaying related posts by tags or category:</p> <pre><code> &lt;?php $max_articles = 4; // How many articles to display echo '&lt;div id="related-articles" class="relatedposts"&gt;&lt;h3&gt;Related articles&lt;/h3&gt;'; $cnt = 0; $article_tags = get_the_tags(); $tags_string = ''; if ($article_tags) { foreach ($article_tags as $article_tag) { $tags_string .= $article_tag-&gt;slug . ','; } } $tag_related_posts = get_posts('exclude=' . $post-&gt;ID . '&amp;numberposts=' . $max_articles . '&amp;tag=' . $tags_string); if ($tag_related_posts) { foreach ($tag_related_posts as $related_post) { $cnt++; echo '&lt;div class="child-' . $cnt . '"&gt;'; echo '&lt;a href="' . get_permalink($related_post-&gt;ID) . '"&gt;'; echo get_the_post_thumbnail($related_post-&gt;ID); echo $related_post-&gt;post_title . '&lt;/a&gt;'; echo incomplete_cat_list; echo '&lt;/div&gt;'; } } // Only if there's not enough tag related articles, // we add some from the same category if ($cnt &lt; $max_articles) { $article_categories = get_the_category($post-&gt;ID); $category_string = ''; foreach($article_categories as $category) { $category_string .= $category-&gt;cat_ID . ','; } $cat_related_posts = get_posts('exclude=' . $post-&gt;ID . '&amp;numberposts=' . $max_articles . '&amp;category=' . $category_string); if ($cat_related_posts) { foreach ($cat_related_posts as $related_post) { $cnt++; if ($cnt &gt; $max_articles) break; echo '&lt;div class="child-' . $cnt . '"&gt;'; echo '&lt;a href="' . get_permalink($related_post-&gt;ID) . '"&gt;'; echo get_the_post_thumbnail($related_post-&gt;ID); echo $related_post-&gt;post_title . '&lt;/a&gt;'; echo incomplete_cat_list; echo '&lt;/div&gt;'; } } } echo '&lt;/div&gt;'; ?&gt; </code></pre> <p><strong>How to call the custom function from functions.php inside above loop?</strong></p>
[ { "answer_id": 288805, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 2, "selected": true, "text": "<p>First you need to pass the post_id to this function to use the post_id inside the <code>get_the_category($post_i...
2017/12/17
[ "https://wordpress.stackexchange.com/questions/288804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133403/" ]
I have a custom function in functions.php that excludes specific category from the category list: ``` function incomplete_cat_list() { $first_time = 1; foreach((get_the_category()) as $category) { if ($category->cat_name != 'Category Name') { if ($first_time == 1) { echo '<a class="cat-list" href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "See all %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; $first_time = 0; } else { } } } } ``` I would like to use it in related posts foreach loop, but I'm not sure how to do it... Here's the code for displaying related posts by tags or category: ``` <?php $max_articles = 4; // How many articles to display echo '<div id="related-articles" class="relatedposts"><h3>Related articles</h3>'; $cnt = 0; $article_tags = get_the_tags(); $tags_string = ''; if ($article_tags) { foreach ($article_tags as $article_tag) { $tags_string .= $article_tag->slug . ','; } } $tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string); if ($tag_related_posts) { foreach ($tag_related_posts as $related_post) { $cnt++; echo '<div class="child-' . $cnt . '">'; echo '<a href="' . get_permalink($related_post->ID) . '">'; echo get_the_post_thumbnail($related_post->ID); echo $related_post->post_title . '</a>'; echo incomplete_cat_list; echo '</div>'; } } // Only if there's not enough tag related articles, // we add some from the same category if ($cnt < $max_articles) { $article_categories = get_the_category($post->ID); $category_string = ''; foreach($article_categories as $category) { $category_string .= $category->cat_ID . ','; } $cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string); if ($cat_related_posts) { foreach ($cat_related_posts as $related_post) { $cnt++; if ($cnt > $max_articles) break; echo '<div class="child-' . $cnt . '">'; echo '<a href="' . get_permalink($related_post->ID) . '">'; echo get_the_post_thumbnail($related_post->ID); echo $related_post->post_title . '</a>'; echo incomplete_cat_list; echo '</div>'; } } } echo '</div>'; ?> ``` **How to call the custom function from functions.php inside above loop?**
First you need to pass the post\_id to this function to use the post\_id inside the `get_the_category($post_id)` ``` function incomplete_cat_list($post_id = '') { global $post; $post_id = ($post_id) ? $post_id : $post->ID; $first_time = 1; $categories = get_the_category($post_id); foreach($categories as $category) { if ($category->cat_name != 'Category Name') { if ($first_time == 1) { echo '<a class="cat-list" href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "See all %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; $first_time = 0; } else { } } } } ``` This function already `echo` so you don't need to echo it again. So you should call it like this. ``` incomplete_cat_list($related_post->ID); ``` Another thing if you want to stop the loop after you get the first category instead of using this `$first_time` variable just use `break;` to stop the loop.
288,831
<p>In my archive I have tipical loop</p> <pre><code>if ( have_posts() ) : /* Start the Loop */ while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', get_post_format() ); endwhile; wp_reset_postdata(); else : get_template_part( 'template-parts/content', 'none' ); endif; </code></pre> <p>And in my sidebar I have a plugin widget which also calls new wp_query to display the recent posts.</p> <pre><code>$query = new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' =&gt; $number, 'no_found_rows' =&gt; true, 'post_status' =&gt; 'publish', 'ignore_sticky_posts' =&gt; true ) ) ); </code></pre> <p>So far so good. But then I need to add filter for my categories to display and custom posts types: </p> <pre><code>function mvp_add_custom_types( $query ) { if( is_category() || is_tag() || is_date() &amp;&amp; empty( $query-&gt;query_vars['suppress_filters'] ) ) { $query-&gt;set( 'post_type', array( 'post', 'nav_menu_item', 'mvp_projects' )); return $query; } } add_filter( 'pre_get_posts', 'mvp_add_custom_types' ); </code></pre> <p>Which suddenly starting to break the other query. How can I use both of this queries with the filter applied to only theme related(the other query is from a plugin)?</p>
[ { "answer_id": 288837, "author": "WhirledPress", "author_id": 133443, "author_profile": "https://wordpress.stackexchange.com/users/133443", "pm_score": 1, "selected": false, "text": "<p>I'm not entirely sure, but it looks like you need another conditional in your filter. Right now, it fi...
2017/12/17
[ "https://wordpress.stackexchange.com/questions/288831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48915/" ]
In my archive I have tipical loop ``` if ( have_posts() ) : /* Start the Loop */ while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', get_post_format() ); endwhile; wp_reset_postdata(); else : get_template_part( 'template-parts/content', 'none' ); endif; ``` And in my sidebar I have a plugin widget which also calls new wp\_query to display the recent posts. ``` $query = new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true ) ) ); ``` So far so good. But then I need to add filter for my categories to display and custom posts types: ``` function mvp_add_custom_types( $query ) { if( is_category() || is_tag() || is_date() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'post', 'nav_menu_item', 'mvp_projects' )); return $query; } } add_filter( 'pre_get_posts', 'mvp_add_custom_types' ); ``` Which suddenly starting to break the other query. How can I use both of this queries with the filter applied to only theme related(the other query is from a plugin)?
I got this sorted, by adding additional contional statement and wrapped OR statements in brackets: ``` function mvp_add_custom_types( $query ) { if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'post', 'nav_menu_item', 'mvp_projects' )); return $query; } } add_filter( 'pre_get_posts', 'mvp_add_custom_types' ); ```
288,854
<p>I have this code:</p> <pre><code>@font-face { font-family: 'Miller Banner Light'; src: url('fonts/Miller-Banner-Light-01.eot'); /* IE9 Compat Modes */ src: url('fonts/Miller-Banner-Light-01.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('fonts/Miller-Banner-Light-01.woff') format('woff'), /* Pretty Modern Browsers */ url('fonts/Miller-Banner-Light-01.ttf') format('truetype') /* Safari, Android, iOS */ } </code></pre> <p>Which in theory allows to add these fonts to my theme, unfortunately, simply creating the <code>fonts</code> folder and putting in the files doesn't work.</p> <p>I read about having to create a child-theme but is that the only way?</p>
[ { "answer_id": 288837, "author": "WhirledPress", "author_id": 133443, "author_profile": "https://wordpress.stackexchange.com/users/133443", "pm_score": 1, "selected": false, "text": "<p>I'm not entirely sure, but it looks like you need another conditional in your filter. Right now, it fi...
2017/12/18
[ "https://wordpress.stackexchange.com/questions/288854", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133461/" ]
I have this code: ``` @font-face { font-family: 'Miller Banner Light'; src: url('fonts/Miller-Banner-Light-01.eot'); /* IE9 Compat Modes */ src: url('fonts/Miller-Banner-Light-01.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('fonts/Miller-Banner-Light-01.woff') format('woff'), /* Pretty Modern Browsers */ url('fonts/Miller-Banner-Light-01.ttf') format('truetype') /* Safari, Android, iOS */ } ``` Which in theory allows to add these fonts to my theme, unfortunately, simply creating the `fonts` folder and putting in the files doesn't work. I read about having to create a child-theme but is that the only way?
I got this sorted, by adding additional contional statement and wrapped OR statements in brackets: ``` function mvp_add_custom_types( $query ) { if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'post', 'nav_menu_item', 'mvp_projects' )); return $query; } } add_filter( 'pre_get_posts', 'mvp_add_custom_types' ); ```
288,868
<p>I'm trying to disable author's link when author's name is displayed. I don't want anything that links to the author archive. Just text without <code>&lt;a href&gt;</code>.</p> <p>What template or file should I edit? I tried the theme template but couldn't find anything, maybe it's something related to the wp files </p>
[ { "answer_id": 288880, "author": "Antonio", "author_id": 78763, "author_profile": "https://wordpress.stackexchange.com/users/78763", "pm_score": 3, "selected": true, "text": "<p>You have actually two problems to solve here:</p>\n\n<ul>\n<li><p>The first one is to remove the HTML link, wh...
2017/12/18
[ "https://wordpress.stackexchange.com/questions/288868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89820/" ]
I'm trying to disable author's link when author's name is displayed. I don't want anything that links to the author archive. Just text without `<a href>`. What template or file should I edit? I tried the theme template but couldn't find anything, maybe it's something related to the wp files
You have actually two problems to solve here: * The first one is to remove the HTML link, which you are trying to achieve right now. As you read in the comments, it depends on your theme. You could find it looking for the exact HTML displayed around the author name (CSS classes etc), and then seeking for it in the files of the theme (including the WordPress folder perhaps) with an editor. * The second issue is less evident but probably more important: you have to actual remove that page. If you just remove the links from your template, the pages will be always visible reaching the URL `http://yousite.com/author/username/`. Getting inspiration by the way SEO Yoast does, you can disable the author archive page with a code like this: ``` function disable_author_page() { global $wp_query; // If an author page is requested, redirects to the home page if ( $wp_query->is_author ) { wp_safe_redirect( get_bloginfo( 'url' ), 301 ); exit; } } add_action( 'wp', 'disable_author_page' ); ```
288,995
<p>Using pure PHP code inside WordPress I am having trouble on getting the <code>glob()</code> work to generate image source.</p> <pre><code>&lt;div class="carousel-inner" role="listbox" style="height=600px; width=1000px;"&gt; &lt;?php $directory = "http://geocaa.com/wp-content/themes/Booting/img/services/"; $images = glob($directory . "*.png"); foreach($images as $image) { echo '&lt;div class="dynamic item"&gt;'; echo ' &lt;img src="'.$image.'" alt="..."&gt;'; echo ' &lt;/div&gt;'; } ?&gt; &lt;/div&gt; </code></pre> <p>As you can see I tried to hardcoded the <code>$directory</code> as <code>"http://geocaa.com/wp-content/themes/Booting/img/services/";</code> and also I already investigate on these two Post<a href="https://stackoverflow.com/questions/19295175/wordpress-php-glob-not-working"> [Post 1</a> &amp; <a href="https://stackoverflow.com/questions/42030975/wordpress-using-glob-returns-an-empty-array">Post 2</a> ] regarding the same issues but the solutions there still not working for me!</p> <p>The <code>get_theme_root()</code> retuns nothing but the <code>get_template_directory()</code> is returning something which is more like</p> <pre><code>$images = glob(get_template_directory().$directory . "*.png"); </code></pre> <blockquote> <p>/home/vcbb/public_html/wp-content/themes/geocaa/img/services/img.png</p> </blockquote> <p>and useless for image src</p> <p>I also tried <code>get_template_directory_uri()</code> but still getting empty array</p>
[ { "answer_id": 288996, "author": "Elex", "author_id": 113687, "author_profile": "https://wordpress.stackexchange.com/users/113687", "pm_score": 0, "selected": false, "text": "<p>I think you just have to try <code>get_stylesheet_directory()</code>.</p>\n\n<pre><code>$images = glob(get_sty...
2017/12/19
[ "https://wordpress.stackexchange.com/questions/288995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35444/" ]
Using pure PHP code inside WordPress I am having trouble on getting the `glob()` work to generate image source. ``` <div class="carousel-inner" role="listbox" style="height=600px; width=1000px;"> <?php $directory = "http://geocaa.com/wp-content/themes/Booting/img/services/"; $images = glob($directory . "*.png"); foreach($images as $image) { echo '<div class="dynamic item">'; echo ' <img src="'.$image.'" alt="...">'; echo ' </div>'; } ?> </div> ``` As you can see I tried to hardcoded the `$directory` as `"http://geocaa.com/wp-content/themes/Booting/img/services/";` and also I already investigate on these two Post [[Post 1](https://stackoverflow.com/questions/19295175/wordpress-php-glob-not-working) & [Post 2](https://stackoverflow.com/questions/42030975/wordpress-using-glob-returns-an-empty-array) ] regarding the same issues but the solutions there still not working for me! The `get_theme_root()` retuns nothing but the `get_template_directory()` is returning something which is more like ``` $images = glob(get_template_directory().$directory . "*.png"); ``` > > /home/vcbb/public\_html/wp-content/themes/geocaa/img/services/img.png > > > and useless for image src I also tried `get_template_directory_uri()` but still getting empty array
You should use *paths* with `glob`, not *URLs*. But `src` attributes needs URLs. So something like this should work: ``` $base_dir = trailingslashit(get_template_directory()); $dir = 'img/services/'; $images = glob($base_dir.$dir.'*.png'); foreach($images as $image) { $url = get_theme_file_uri($dir.basename($image)); printf('<div class="dynamic item"><img src="%s" alt=""></div>', esc_url($url)); } ``` Where I make use of: * [`get_template_directory`](https://developer.wordpress.org/reference/functions/get_template_directory/) To obtain the root path of (parent) theme * [`basename`](http://php.net/manual/en/function.basename.php) to obtain just the *file name* of the current image file path * [`get_theme_file_uri`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) to obtain the full URL of the image, in a child-theme friendly way: if the image is found in child theme it will be used from there, otherwise will be used from parent theme.
288,998
<p>I'm trying to use for the second time the hook wp_ajax to call a php method from a Class inside my js script. I did it one time with success but this time, it does not work. I don't know why.</p> <p>Context : I do this in an addon, not in my main plugin.</p> <p>I did all these following steps :</p> <p><strong>Add my function in my class <em>FooClass</em></strong></p> <pre><code>namespace Namespace\Common; class FooClass{ public static function getItems()... public static function getItemsByAjax() { error_log( 'getItemsByAjax' ); $f_options = self::getItems( $_POST[ 'foo_type' ] ); $json = json_encode( $f_options ); echo $json; wp_die(); } } </code></pre> <p><strong>Init this function inside another Class called on an admin page</strong></p> <pre><code>class OtherClass{ public function __construct(){ add_action('wp_ajax_getItemsByAjax', array( 'Namespace\Common\FooClass', 'getItemsByAjax' ) ); } } </code></pre> <p><strong>Usage in my jQueryScript</strong></p> <pre><code>jQuery( function($) { $(document).ready( function() { $('.my-button').click(function() { var data = { 'action': 'getItemsByAjax', 'foo_type' : 'x' }; $.post( ajaxurl, data, function( response ) { var jsonObj = JSON.parse( response ); console.dir( jsonObj ); }); }); }); </code></pre> <p>});</p> <p><em>getItemsByAjax()</em> is never called. What could I have forgotten ? </p>
[ { "answer_id": 289002, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 1, "selected": false, "text": "<p>Finally I've found the problem in your code.\nYou've forgotten \\ on namespace path.</p>\n\n<pre><code>...
2017/12/19
[ "https://wordpress.stackexchange.com/questions/288998", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I'm trying to use for the second time the hook wp\_ajax to call a php method from a Class inside my js script. I did it one time with success but this time, it does not work. I don't know why. Context : I do this in an addon, not in my main plugin. I did all these following steps : **Add my function in my class *FooClass*** ``` namespace Namespace\Common; class FooClass{ public static function getItems()... public static function getItemsByAjax() { error_log( 'getItemsByAjax' ); $f_options = self::getItems( $_POST[ 'foo_type' ] ); $json = json_encode( $f_options ); echo $json; wp_die(); } } ``` **Init this function inside another Class called on an admin page** ``` class OtherClass{ public function __construct(){ add_action('wp_ajax_getItemsByAjax', array( 'Namespace\Common\FooClass', 'getItemsByAjax' ) ); } } ``` **Usage in my jQueryScript** ``` jQuery( function($) { $(document).ready( function() { $('.my-button').click(function() { var data = { 'action': 'getItemsByAjax', 'foo_type' : 'x' }; $.post( ajaxurl, data, function( response ) { var jsonObj = JSON.parse( response ); console.dir( jsonObj ); }); }); }); ``` }); *getItemsByAjax()* is never called. What could I have forgotten ?
After several tests, and some help inside the comments, I detect the right problem : > > if xhr response returns 0 means that the ajax function does not be hooked. > > > The solution in my case was to init my addon classes with a right hook like [here](https://wordpress.stackexchange.com/questions/289112/how-to-init-an-addon-correctly-after-the-main-plugin).
289,048
<p>While there may be another or better way to do it, all I need is this last snippet to make this do exactly what I need. So, I hope anyone here can and is willing to help me get it working as I need?</p> <p>First, in the WP back-end I created and published a blank page (using a custom template) that is a required part of this formula I concocted. </p> <p>Each time a new page is created in the WP back-end, the blank page (the custom template php file) needs to grab and display 'object1' from that newly created page. So any time a new page is created in the WP back-end, 'object1' of that new page will be pulled into the published page. How do I achieve this? Here is the code I am working with:</p> <pre><code>&lt;?php the_field('object1', /*code for any newly created page rather than a specific number*/ ); ?&gt; </code></pre> <p>What is the code to input after 'object1', for any newly created page?</p> <p>I learned through trial and error these don't produce the result I'm needing:</p> <pre><code>&lt;?php the_field('object1'); ?&gt; </code></pre> <p>^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template).</p> <pre><code>&lt;?php the_field('object1', 3 ); ?&gt; </code></pre> <p>^^ The above code resulted in getting 'object1' from the page with post id number 3 in the url.</p> <pre><code>&lt;?php the_field('object1', $post-&gt;ID ); ?&gt; </code></pre> <p>^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template).</p> <p>Many thanks for any guidance given.</p> <hr> <p><code>$post-&gt;ID</code> calls for current page, but what is the code to call for any new page created and published in WordPress?</p>
[ { "answer_id": 289002, "author": "Anton Lukin", "author_id": 126253, "author_profile": "https://wordpress.stackexchange.com/users/126253", "pm_score": 1, "selected": false, "text": "<p>Finally I've found the problem in your code.\nYou've forgotten \\ on namespace path.</p>\n\n<pre><code>...
2017/12/20
[ "https://wordpress.stackexchange.com/questions/289048", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58726/" ]
While there may be another or better way to do it, all I need is this last snippet to make this do exactly what I need. So, I hope anyone here can and is willing to help me get it working as I need? First, in the WP back-end I created and published a blank page (using a custom template) that is a required part of this formula I concocted. Each time a new page is created in the WP back-end, the blank page (the custom template php file) needs to grab and display 'object1' from that newly created page. So any time a new page is created in the WP back-end, 'object1' of that new page will be pulled into the published page. How do I achieve this? Here is the code I am working with: ``` <?php the_field('object1', /*code for any newly created page rather than a specific number*/ ); ?> ``` What is the code to input after 'object1', for any newly created page? I learned through trial and error these don't produce the result I'm needing: ``` <?php the_field('object1'); ?> ``` ^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template). ``` <?php the_field('object1', 3 ); ?> ``` ^^ The above code resulted in getting 'object1' from the page with post id number 3 in the url. ``` <?php the_field('object1', $post->ID ); ?> ``` ^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template). Many thanks for any guidance given. --- `$post->ID` calls for current page, but what is the code to call for any new page created and published in WordPress?
After several tests, and some help inside the comments, I detect the right problem : > > if xhr response returns 0 means that the ajax function does not be hooked. > > > The solution in my case was to init my addon classes with a right hook like [here](https://wordpress.stackexchange.com/questions/289112/how-to-init-an-addon-correctly-after-the-main-plugin).
289,063
<p>I've created some custom post-types using the Pods framework, however the the solution to my question should be the same regardless of pods. My custom types are <code>event</code>, <code>team</code>, <code>achievement</code>, <code>achievementunlock</code>. Each <code>team</code> and <code>achievement</code> belongs to an <code>event</code>, each <code>team</code> has a number of users assigned, and each user can post an <code>achievementunlock</code> and choose from a list of <code>achievements</code>.</p> <p>I'd like to create a page which displays an overview of which achievements have been "unlocked", i.e. a user has posted an achievementunlock post for.</p> <p>Something like this</p> <pre><code>Event1Name | Team1 |Team2 | Bob | Steve | Scott | Mary | Achievement1Name | View | - | - | View | Achievement2Name | - | View | - | View | Achievement3Name | - | - | View | | Total | 1 | 1 | 1 | 2 | Team Total | 2 | 3 | Event2Name ..... </code></pre> <p>I'd need to be able to iterate all objects and see their properties. I.e. An <code>achievement</code> post is posted by Bob, I need to be able to also see which <code>team</code> he belongs to, and which <code>event</code> that <code>team</code> belongs to, etc.</p> <p>How can I fetch my objects which I can iterate over them with ease, and how do I setup such a page in wordpress? Thanks!</p>
[ { "answer_id": 289175, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 2, "selected": false, "text": "<p>It seems you are asking for a complete custom funcionality,</p>\n\n<p>To add menu, you can use this.<...
2017/12/20
[ "https://wordpress.stackexchange.com/questions/289063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133576/" ]
I've created some custom post-types using the Pods framework, however the the solution to my question should be the same regardless of pods. My custom types are `event`, `team`, `achievement`, `achievementunlock`. Each `team` and `achievement` belongs to an `event`, each `team` has a number of users assigned, and each user can post an `achievementunlock` and choose from a list of `achievements`. I'd like to create a page which displays an overview of which achievements have been "unlocked", i.e. a user has posted an achievementunlock post for. Something like this ``` Event1Name | Team1 |Team2 | Bob | Steve | Scott | Mary | Achievement1Name | View | - | - | View | Achievement2Name | - | View | - | View | Achievement3Name | - | - | View | | Total | 1 | 1 | 1 | 2 | Team Total | 2 | 3 | Event2Name ..... ``` I'd need to be able to iterate all objects and see their properties. I.e. An `achievement` post is posted by Bob, I need to be able to also see which `team` he belongs to, and which `event` that `team` belongs to, etc. How can I fetch my objects which I can iterate over them with ease, and how do I setup such a page in wordpress? Thanks!
Although Rahilesh pointed me in the right direction and is upvoted for that, I feel that I can provide a more complete answer now that I've got things running. First create a new PHP template file, create a page and connect it to that template and add the page to your menu. In that file you can now query the wordpress databases using the `$wpdb` object as Rajilesh suggested. You can access any of the wordpress tables. Data on each post is in posts, and anything added through the Pods framework is found in postmeta where each item is has a postID and meta\_key which is set in your Pods settings. For example: ``` $posts = $wpdb->get_results( " SELECT * FROM $wpdb->posts WHERE (post_type = 'event' OR post_type = 'team'"); ``` Note: This will include all posts, so it may be a good idea check include some checks to avoid trashed items and drafts in your SQL query as such: ``` post_status <> 'draft' AND post_status <> 'auto-draft' AND post_status <> 'trash' etc... ``` Some basic data fields use the name directly, while relationship and media fields use a `_pods_` prefix. Relationships will be arrays which hold the ID of their partner. ``` $meta = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_pods_unlocks' OR meta_key = 'achievement' OR ``` If your setup is a bit complex as mine was, it may be a good idea to build an object oriented approach and create objects for each of your Pods. Now that you've gained access to all your data, you can output it in any way you see fit with custom code such as: ``` usort($event->Teams, "sortTeams"); echo "<h3>"; for ($i = 0; $i < count($event->Teams); $i++) { $team = $event->Teams[$i]; echo ($i + 1) . ": $team->Title ($team->Score)<br/>"; } echo "</h3>"; ``` Hopefully this helps someone along the way!
289,110
<p>I'm using the Enigma theme in my webpage and I want to hide the title of some posts without using any plugins. Every tutorial I find on the internet teaches me how to do it in a incompatible way for my theme. The TAGs of the HTML and the CSS code aren't matching with the structure of mine. So I need some help to do it.</p>
[ { "answer_id": 289175, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 2, "selected": false, "text": "<p>It seems you are asking for a complete custom funcionality,</p>\n\n<p>To add menu, you can use this.<...
2017/12/20
[ "https://wordpress.stackexchange.com/questions/289110", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133600/" ]
I'm using the Enigma theme in my webpage and I want to hide the title of some posts without using any plugins. Every tutorial I find on the internet teaches me how to do it in a incompatible way for my theme. The TAGs of the HTML and the CSS code aren't matching with the structure of mine. So I need some help to do it.
Although Rahilesh pointed me in the right direction and is upvoted for that, I feel that I can provide a more complete answer now that I've got things running. First create a new PHP template file, create a page and connect it to that template and add the page to your menu. In that file you can now query the wordpress databases using the `$wpdb` object as Rajilesh suggested. You can access any of the wordpress tables. Data on each post is in posts, and anything added through the Pods framework is found in postmeta where each item is has a postID and meta\_key which is set in your Pods settings. For example: ``` $posts = $wpdb->get_results( " SELECT * FROM $wpdb->posts WHERE (post_type = 'event' OR post_type = 'team'"); ``` Note: This will include all posts, so it may be a good idea check include some checks to avoid trashed items and drafts in your SQL query as such: ``` post_status <> 'draft' AND post_status <> 'auto-draft' AND post_status <> 'trash' etc... ``` Some basic data fields use the name directly, while relationship and media fields use a `_pods_` prefix. Relationships will be arrays which hold the ID of their partner. ``` $meta = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = '_pods_unlocks' OR meta_key = 'achievement' OR ``` If your setup is a bit complex as mine was, it may be a good idea to build an object oriented approach and create objects for each of your Pods. Now that you've gained access to all your data, you can output it in any way you see fit with custom code such as: ``` usort($event->Teams, "sortTeams"); echo "<h3>"; for ($i = 0; $i < count($event->Teams); $i++) { $team = $event->Teams[$i]; echo ($i + 1) . ": $team->Title ($team->Score)<br/>"; } echo "</h3>"; ``` Hopefully this helps someone along the way!
289,169
<p>I want to create an A to Z index listing of all posts from a specific custom post type. This is the code so far:</p> <pre><code>&lt;?php /** * The Template for displaying archive series. * * Theme: Default */ get_header(); ?&gt; &lt;div id="content"&gt; &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array('paged' =&gt; $paged,'posts_per_page' =&gt; -1,'post_type' =&gt; 'series_type','post_status' =&gt; 'publish','orderby' =&gt; 'title','order' =&gt; 'asc'); $fruits = new WP_Query($args); if($fruits-&gt;have_posts()){ $current_first_letter = ''; $t = array(); $s = array(); while($fruits-&gt;have_posts()){ $fruits-&gt;the_post(); $title = get_the_title(); if(is_string($title)){ $first_letter = strtoupper($title[0]); if($first_letter != $current_first_letter){ $t[] = $first_letter; $current_first_letter = $first_letter; } } $s[$first_letter][] = get_the_title(); } } $t = array_unique($t); $tc = count($t); $sc = count($s); for($i=0; $i&lt;$tc; $i++){ ?&gt; &lt;div&gt; &lt;h4&gt;&lt;?php echo $t[$i]; ?&gt;&lt;/h4&gt; &lt;ul&gt; &lt;?php foreach($s as $key =&gt; $value){ if($key == $t[$i]){ $vc = count($value); for($j=0; $j&lt;$vc; $j++){ ?&gt; &lt;li&gt;&lt;?php echo $value[$j]; ?&gt;&lt;/li&gt; &lt;?php } } } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } if($fruits-&gt;max_num_pages &gt; 1){ ?&gt; &lt;nav class="prev-next-posts"&gt; &lt;div class="prev-posts-link"&gt; &lt;?php echo get_next_posts_link( 'Older Entries', $fruits-&gt;max_num_pages ); ?&gt; &lt;/div&gt; &lt;div class="next-posts-link"&gt; &lt;?php echo get_previous_posts_link( 'Newer Entries' ); ?&gt; &lt;/div&gt; &lt;/nav&gt; &lt;?php } ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;/div&gt;&lt;!-- #content --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>The problem is I don't know how to make all of them as hyperlinks instead of raw text. Can anyone help me fix the code?</p>
[ { "answer_id": 289170, "author": "Elex", "author_id": 113687, "author_profile": "https://wordpress.stackexchange.com/users/113687", "pm_score": 4, "selected": true, "text": "<p>Ok, you just have to make a loop with first letter check. WordPress query will handle the <code>post_title</cod...
2017/12/21
[ "https://wordpress.stackexchange.com/questions/289169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100682/" ]
I want to create an A to Z index listing of all posts from a specific custom post type. This is the code so far: ``` <?php /** * The Template for displaying archive series. * * Theme: Default */ get_header(); ?> <div id="content"> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array('paged' => $paged,'posts_per_page' => -1,'post_type' => 'series_type','post_status' => 'publish','orderby' => 'title','order' => 'asc'); $fruits = new WP_Query($args); if($fruits->have_posts()){ $current_first_letter = ''; $t = array(); $s = array(); while($fruits->have_posts()){ $fruits->the_post(); $title = get_the_title(); if(is_string($title)){ $first_letter = strtoupper($title[0]); if($first_letter != $current_first_letter){ $t[] = $first_letter; $current_first_letter = $first_letter; } } $s[$first_letter][] = get_the_title(); } } $t = array_unique($t); $tc = count($t); $sc = count($s); for($i=0; $i<$tc; $i++){ ?> <div> <h4><?php echo $t[$i]; ?></h4> <ul> <?php foreach($s as $key => $value){ if($key == $t[$i]){ $vc = count($value); for($j=0; $j<$vc; $j++){ ?> <li><?php echo $value[$j]; ?></li> <?php } } } ?> </ul> </div> <?php } if($fruits->max_num_pages > 1){ ?> <nav class="prev-next-posts"> <div class="prev-posts-link"> <?php echo get_next_posts_link( 'Older Entries', $fruits->max_num_pages ); ?> </div> <div class="next-posts-link"> <?php echo get_previous_posts_link( 'Newer Entries' ); ?> </div> </nav> <?php } ?> <?php wp_reset_postdata(); ?> </div><!-- #content --> <?php get_footer(); ?> ``` The problem is I don't know how to make all of them as hyperlinks instead of raw text. Can anyone help me fix the code?
Ok, you just have to make a loop with first letter check. WordPress query will handle the `post_title` `ASC` order. **EDIT :** I use get\_permalink() within the loop to get URL (<https://developer.wordpress.org/reference/functions/get_permalink/>) ``` $series = new WP_Query(array( 'posts_per_page' => -1, 'post_type' => 'series_type', 'orderby' => 'title', 'order' => 'asc' )); if($series->have_posts()) { $letter = ''; while($series->have_posts()) { $series->the_post(); // Check the current letter is the same that the first of the title if($letter != strtoupper(get_the_title()[0])) { echo ($letter != '') ? '</ul></div>' : ''; $letter = strtoupper(get_the_title()[0]); echo '<div><ul><h4>'.strtoupper(get_the_title()[0]).'</h4>'; } echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; } } ```
289,258
<p>I'm hoping someone can help as I have searched and cannot find an answer...</p> <p>I am using a loop in a shortcode to display a list of related items and I'm having trouble working out the logic of selecting multiple categories in an AND parameter.</p> <p>For example, I have a category structure like this:</p> <pre><code>Products (id: 1) Prod A (id: 2) Prod B (id: 3) Services (id: 4) Service A (id: 5) Service B (id: 6) Overview (id: 7) </code></pre> <p>What I would like to do is show all posts that are categorised as id 7 AND specific other IDs.</p> <p>For example:</p> <pre><code>'category__and' =&gt; array(7,2), AND 'category__and' =&gt; array(7,5), </code></pre> <p>Which would show 2 results - posts categorised as (Overview AND Prod A) AND (Overview AND Service A).</p> <p>Everything works if I only want to show one selection (eg. Overview AND Prod A) but I can't work out how to show multiples.</p> <p>Changing it to category__in does not work because that shows all posts categorised as Overview including Prod B and Service B, in the above example. It's also not practical to use category__not_in to exclude categories because the list is quite long and will change (unless there's a way of programmatically working out which categories to exclude?).</p> <p>Is there a way of using multiple pairs of category__and values, or a way of coding multiple loops for WP_Query to achieve this?</p> <p>I hope that gives you enough to go on. Thanks in advance!</p>
[ { "answer_id": 289239, "author": "Gordon Smith", "author_id": 73331, "author_profile": "https://wordpress.stackexchange.com/users/73331", "pm_score": 2, "selected": false, "text": "<p>To shorten your search the article points out that the suggested code is old and that you can now use th...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289258", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133687/" ]
I'm hoping someone can help as I have searched and cannot find an answer... I am using a loop in a shortcode to display a list of related items and I'm having trouble working out the logic of selecting multiple categories in an AND parameter. For example, I have a category structure like this: ``` Products (id: 1) Prod A (id: 2) Prod B (id: 3) Services (id: 4) Service A (id: 5) Service B (id: 6) Overview (id: 7) ``` What I would like to do is show all posts that are categorised as id 7 AND specific other IDs. For example: ``` 'category__and' => array(7,2), AND 'category__and' => array(7,5), ``` Which would show 2 results - posts categorised as (Overview AND Prod A) AND (Overview AND Service A). Everything works if I only want to show one selection (eg. Overview AND Prod A) but I can't work out how to show multiples. Changing it to category\_\_in does not work because that shows all posts categorised as Overview including Prod B and Service B, in the above example. It's also not practical to use category\_\_not\_in to exclude categories because the list is quite long and will change (unless there's a way of programmatically working out which categories to exclude?). Is there a way of using multiple pairs of category\_\_and values, or a way of coding multiple loops for WP\_Query to achieve this? I hope that gives you enough to go on. Thanks in advance!
To shorten your search the article points out that the suggested code is old and that you can now use this plug-in to define custom colors: [Central Color Palette](https://wordpress.org/plugins/kt-tinymce-color-grid/)
289,269
<p>I have create a custom meta key into the post table and it's value is in serialized form now when I dump the value it is giving me like this</p> <blockquote> <p>Array ( [0] => a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:2;i:0;a:0:{}}";}} )</p> </blockquote> <p>I want to get user_id and product_id from it. The main idea is to hide a button for those user whose ID's are stored into this meta_key for the particular product whose ID are in this serialized array as well any idea how to do that I have tried the following code but nothing happens</p> <pre><code>$next_in_line = get_post_meta(esc_attr($product-&gt;get_id()), '_next_in_line'); print_r($next_in_line); $unserilize_data = unserialize($next_in_line); print_r($unserilize_data['0']); </code></pre> <p>But is giving me bool(false) and when I use this function</p> <pre><code>$next_in_line = get_post_meta(esc_attr($product-&gt;get_id()), '_next_in_line'); print_r($next_in_line); $un_data = maybe_unserialize($next_in_line); print_r($un_data['0']); </code></pre> <p>it is returning me values in the following format</p> <blockquote> <p>a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:2;i:0;a:0:{}}";}}</p> </blockquote> <p>Now how can I make the condition that I have mentioned above I am blank at this point please some one help me out. Thank you in advance</p> <p><strong>UPDATE</strong></p> <p>I am storing data like this</p> <pre><code>function nextInLine(){ $product_id = $_POST['product_id']; $user_id = get_current_user_id(); $next_customer_meta = get_post_meta($product_id, '_next_in_line'); if($next_customer_meta == ''){ $meta_array = array( 'product_id' =&gt; $product_id, 'user_id' =&gt; $user_id ); $meta_value = maybe_serialize($meta_array); } else { $meta_array = array( 'product_id' =&gt; $product_id, 'user_id' =&gt; $user_id ); array_push($meta_array, $next_customer_meta); $meta_value = maybe_serialize($meta_array); } var_dump($meta_value); update_post_meta($product_id, '_next_in_line', $meta_value); return true; } add_action('wp_ajax_nextInLine', 'nextInLine'); add_action('wp_ajax_nopriv_nextInLine', 'nextInLine'); </code></pre>
[ { "answer_id": 289264, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>As stated in the <a href=\"https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132946/" ]
I have create a custom meta key into the post table and it's value is in serialized form now when I dump the value it is giving me like this > > Array ( [0] => a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:2;i:0;a:0:{}}";}} ) > > > I want to get user\_id and product\_id from it. The main idea is to hide a button for those user whose ID's are stored into this meta\_key for the particular product whose ID are in this serialized array as well any idea how to do that I have tried the following code but nothing happens ``` $next_in_line = get_post_meta(esc_attr($product->get_id()), '_next_in_line'); print_r($next_in_line); $unserilize_data = unserialize($next_in_line); print_r($unserilize_data['0']); ``` But is giving me bool(false) and when I use this function ``` $next_in_line = get_post_meta(esc_attr($product->get_id()), '_next_in_line'); print_r($next_in_line); $un_data = maybe_unserialize($next_in_line); print_r($un_data['0']); ``` it is returning me values in the following format > > a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:2;i:0;a:0:{}}";}} > > > Now how can I make the condition that I have mentioned above I am blank at this point please some one help me out. Thank you in advance **UPDATE** I am storing data like this ``` function nextInLine(){ $product_id = $_POST['product_id']; $user_id = get_current_user_id(); $next_customer_meta = get_post_meta($product_id, '_next_in_line'); if($next_customer_meta == ''){ $meta_array = array( 'product_id' => $product_id, 'user_id' => $user_id ); $meta_value = maybe_serialize($meta_array); } else { $meta_array = array( 'product_id' => $product_id, 'user_id' => $user_id ); array_push($meta_array, $next_customer_meta); $meta_value = maybe_serialize($meta_array); } var_dump($meta_value); update_post_meta($product_id, '_next_in_line', $meta_value); return true; } add_action('wp_ajax_nextInLine', 'nextInLine'); add_action('wp_ajax_nopriv_nextInLine', 'nextInLine'); ```
As stated in the [announcement post](https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/): > > A few account security enhancements have gone into WordPress 4.9. The > intention is to make it more difficult for an attacker to take over a > user account or a site by changing the email address associated with > the user or the site, and also to reduce the chance of a mistaken or > erroneous change causing you to get locked out. > > >
289,281
<p>I'm working on a relationship filter using <a href="https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/" rel="nofollow noreferrer">this documentary</a>.</p> <p>I made so far but can't make my return value. Normally in a custom Template I just echo it, but it's different in a function I think.</p> <pre><code>function soup_filter( $args, $field, $post_id ) { $args = array('post_type' =&gt; 'menu'); $query = new WP_Query( $args ); $soups = get_field('soups'); foreach ($soups as $soup) { //return value stored here in $soup } // return return $args; } add_filter('acf/fields/relationship/query/key=field_59f736725fe5d', 'soup_filter', 10, 3); </code></pre>
[ { "answer_id": 289264, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>As stated in the <a href=\"https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289281", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133469/" ]
I'm working on a relationship filter using [this documentary](https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/). I made so far but can't make my return value. Normally in a custom Template I just echo it, but it's different in a function I think. ``` function soup_filter( $args, $field, $post_id ) { $args = array('post_type' => 'menu'); $query = new WP_Query( $args ); $soups = get_field('soups'); foreach ($soups as $soup) { //return value stored here in $soup } // return return $args; } add_filter('acf/fields/relationship/query/key=field_59f736725fe5d', 'soup_filter', 10, 3); ```
As stated in the [announcement post](https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/): > > A few account security enhancements have gone into WordPress 4.9. The > intention is to make it more difficult for an attacker to take over a > user account or a site by changing the email address associated with > the user or the site, and also to reduce the chance of a mistaken or > erroneous change causing you to get locked out. > > >
289,287
<p><code>ABSPATH</code> outputs like <code>C/:docs/http_root/public_html/</code> or <code>/home/userXXXXX/public_html</code> (or etc, depending on server).</p> <p>However, I want to get the file location according to its relative path from <code>ABSPATH</code>. How to achieve that?</p> <p>i.e. I want to get from file:</p> <pre><code>C/:docs/http_root/public_html/some_folder/file.php ----&gt; /some_folder/file.php </code></pre> <p>P.S. </p> <p>1) <code>request_uri</code> and <code>php_self</code> wont help in this case.</p> <p>2) Maybe it's surprising but even this doesn't help on all servers: <code>str_replace(ABSPATH, '', __DIR__)</code> </p>
[ { "answer_id": 289264, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>As stated in the <a href=\"https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289287", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
`ABSPATH` outputs like `C/:docs/http_root/public_html/` or `/home/userXXXXX/public_html` (or etc, depending on server). However, I want to get the file location according to its relative path from `ABSPATH`. How to achieve that? i.e. I want to get from file: ``` C/:docs/http_root/public_html/some_folder/file.php ----> /some_folder/file.php ``` P.S. 1) `request_uri` and `php_self` wont help in this case. 2) Maybe it's surprising but even this doesn't help on all servers: `str_replace(ABSPATH, '', __DIR__)`
As stated in the [announcement post](https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/): > > A few account security enhancements have gone into WordPress 4.9. The > intention is to make it more difficult for an attacker to take over a > user account or a site by changing the email address associated with > the user or the site, and also to reduce the chance of a mistaken or > erroneous change causing you to get locked out. > > >
289,293
<p>I have manually created a role called &quot;event-planner&quot;. I've assigned some capabilities to it and it works as expected. However, if I later set one of the capabilities from true to false (or vice versa), changes won't reflect on WordPress. I think this is related to WordPress not updating the capabilities because if I delete the role and then add the code again, then it will work.</p> <p>Is there a way to &quot;tell&quot; WordPress to update my role capabilities once they were set?</p> <p>Here is my code:</p> <pre class="lang-php prettyprint-override"><code>$result = add_role('event-planner', __('Event Planner'), array( 'read' =&gt; true, 'delete_others_events' =&gt; false, 'delete_private_events' =&gt; true, 'delete_published_events' =&gt; true, 'delete_events' =&gt; true, 'edit_others_events' =&gt; false, 'edit_private_events' =&gt; true, 'edit_published_events' =&gt; true, 'edit_events' =&gt; true, 'publish_events' =&gt; true, 'read_private_events' =&gt; true ) ); </code></pre>
[ { "answer_id": 289294, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>You can use the function <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"nof...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21245/" ]
I have manually created a role called "event-planner". I've assigned some capabilities to it and it works as expected. However, if I later set one of the capabilities from true to false (or vice versa), changes won't reflect on WordPress. I think this is related to WordPress not updating the capabilities because if I delete the role and then add the code again, then it will work. Is there a way to "tell" WordPress to update my role capabilities once they were set? Here is my code: ```php $result = add_role('event-planner', __('Event Planner'), array( 'read' => true, 'delete_others_events' => false, 'delete_private_events' => true, 'delete_published_events' => true, 'delete_events' => true, 'edit_others_events' => false, 'edit_private_events' => true, 'edit_published_events' => true, 'edit_events' => true, 'publish_events' => true, 'read_private_events' => true ) ); ```
`add_role()` will not do anything if the role already exists, so it can't be used to modify capabilities. To modify capabilities use the `add_cap()` and `remove_cap()` method of the `WP_Role` object. You can get a `WP_Role` for your role using `get_role()`: ``` $role = get_role( 'event-planner' ); $role->add_cap( 'edit_others_events' ); ``` Here's the thing though, roles are stored in the database, so adding roles or capabilities are things that shouldn't be happening on every page load. If you want to modify an existing role, you'll need to do it just once. So that means you'll need to do it on theme or plugin activation, or when saving an options page. The same goes for creating the role to begin with. Given that, if this is just a plugin/role that exists on just on your site, you're probably better of just using a plugin like [User Role Editor](https://wordpress.org/plugins/user-role-editor/). If it's a distributed plugin, you could do it in a hook that loads on every page, but just check an option to see if the update has already been done: ``` function wpse_289293_update_role() { // Get current version of user role. $version = get_option( 'wpse_289293_roles_version' ) // Define version number that represents this change. $new_version = 2; // If current version is lower than new version. if ( $version < $new_version ) { // Update the role. $role = get_role( 'event-planner' ); $role->add_cap( 'edit_others_events' ); // Update db to indicate role has been updated. update_option( 'wpse_289293_db_version', $new_version ); } } add_action( 'plugins_loaded', 'wpse_289293_update_role' ); ``` Because the role's capabilities aren't being forced on every page reload this also has the advantage of allowing users to use a user role editor plugin to modify the capabilities themselves. If `add_cap()` was being run on every page load it would overwrite any changes they would make.
289,307
<p>I'm using <a href="https://www.themepunch.com/essgrid-doc/essential-grid-documentation/" rel="nofollow noreferrer">Essential Grid</a> plugin to create a custom meta field for posts. I've created a simple image field. The plan is to add the URL of the featured image. Problem is I'm not sure how to get the physical URL.</p> <p>For instance, I'm trying to get <code>/mysite.com/wp-contents/uploads/my-image.jpg</code>.</p> <p>What's the best and fastest way to get the URL?</p>
[ { "answer_id": 289309, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>If you are trying to retrieve the post's featured image URI, you can use the <a href=\"https://developer.wo...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60386/" ]
I'm using [Essential Grid](https://www.themepunch.com/essgrid-doc/essential-grid-documentation/) plugin to create a custom meta field for posts. I've created a simple image field. The plan is to add the URL of the featured image. Problem is I'm not sure how to get the physical URL. For instance, I'm trying to get `/mysite.com/wp-contents/uploads/my-image.jpg`. What's the best and fastest way to get the URL?
The function to use would be: ``` $url = get_the_post_thumbnail_url(); ``` However, that's not the most helpful for you right now, so we have a meta field with placeholders that you need to swap out for URLs before outputting. breaking that down we get these smaller steps: ``` // grab the field // grab the URL // swap the placeholder out for the URL // output the field ``` So lets do each individual bit: ``` // grab the field $meta = get_post_meta( .... // grab the URL $thumb_url = get_the_post_thumbnail_url(); // swap the thumbnail placeholder out for the URL $meta = str_replace( '%thumbnail%', $thumb_url, $meta ); // output the meta field echo wp_kses_post( $meta ); ``` Notice the `wp_kses_post` which strips out dangerous HTML while letting you keep `img` tags etc
289,321
<p>I tried to make a child theme to change some colors. I used this <a href="https://codex.wordpress.org/Child_Themes" rel="nofollow noreferrer">https://codex.wordpress.org/Child_Themes</a> tutorial, but I still can't get this done. The problem is that I am not able to override some styles, because my stylesheet called "bootstrap.css" is not getting loaded. My functions.php file looks like this</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'child-style', get_template_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version')); wp_enqueue_style( 'child-style', get_template_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()-&gt;get('Version')); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?&gt; </code></pre> <p>These are the files that are getting loaded <a href="https://i.stack.imgur.com/BZaTo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BZaTo.png" alt="enter image description here"></a></p> <p><strong>EDIT 1:</strong> I'm now using this code and it still isn't working</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version')); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()-&gt;get('Version')); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?&gt; </code></pre> <p><strong>EDIT 2:</strong> My bootstrap stylesheet is getting loaded, but for some reason my website is still using another version of it. As you can see it uses 3 times the same styles and the one that is really used is version 3.3.4. and I want to use the one with the blue color which is version 1.0.2 <a href="https://i.stack.imgur.com/SkvA9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SkvA9.png" alt="enter image description here"></a> Version 3.3.4 in the picture and I want to use the bootstrap version 1.0.2. <a href="https://i.stack.imgur.com/9ygYt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ygYt.png" alt="enter image description here"></a> <strong>EDIT 3:</strong> Code from functions.php that I am using at the moment</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_styles = array('maxstore_theme_style', 'maxstore_theme_bootstrap'); // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_styles[0], get_template_directory_uri() . '/style.css' ); wp_enqueue_style( $parent_styles[1], get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', $parent_styles, wp_get_theme()-&gt;get('Version')); wp_enqueue_style( 'child-bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.css', $parent_styles, wp_get_theme()-&gt;get('Version')); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?&gt; </code></pre>
[ { "answer_id": 289322, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<h2>Parent vs Child Themes</h2>\n\n<p><code>get_template_directory_uri</code> always refers to the parent theme ...
2017/12/22
[ "https://wordpress.stackexchange.com/questions/289321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133727/" ]
I tried to make a child theme to change some colors. I used this <https://codex.wordpress.org/Child_Themes> tutorial, but I still can't get this done. The problem is that I am not able to override some styles, because my stylesheet called "bootstrap.css" is not getting loaded. My functions.php file looks like this ``` <?php function my_theme_enqueue_styles() { $parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'child-style', get_template_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version')); wp_enqueue_style( 'child-style', get_template_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version')); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ``` These are the files that are getting loaded [![enter image description here](https://i.stack.imgur.com/BZaTo.png)](https://i.stack.imgur.com/BZaTo.png) **EDIT 1:** I'm now using this code and it still isn't working ``` <?php function my_theme_enqueue_styles() { $parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version')); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version')); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ``` **EDIT 2:** My bootstrap stylesheet is getting loaded, but for some reason my website is still using another version of it. As you can see it uses 3 times the same styles and the one that is really used is version 3.3.4. and I want to use the one with the blue color which is version 1.0.2 [![enter image description here](https://i.stack.imgur.com/SkvA9.png)](https://i.stack.imgur.com/SkvA9.png) Version 3.3.4 in the picture and I want to use the bootstrap version 1.0.2. [![enter image description here](https://i.stack.imgur.com/9ygYt.png)](https://i.stack.imgur.com/9ygYt.png) **EDIT 3:** Code from functions.php that I am using at the moment ``` <?php function my_theme_enqueue_styles() { $parent_styles = array('maxstore_theme_style', 'maxstore_theme_bootstrap'); // This is 'twentyfifteen-style' for the Twenty Fifteen theme. wp_enqueue_style( $parent_styles[0], get_template_directory_uri() . '/style.css' ); wp_enqueue_style( $parent_styles[1], get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', $parent_styles, wp_get_theme()->get('Version')); wp_enqueue_style( 'child-bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.css', $parent_styles, wp_get_theme()->get('Version')); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ```
Parent vs Child Themes ---------------------- `get_template_directory_uri` always refers to the parent theme you can verify this as you always should when things don't load as expected by looking in the console in the browsers dev tools. These would show 404 errors for the CSS files, in the wrong folder. Instead, use `get_stylesheet_directory_uri`, the `stylesheet` family of functions always refer to the current active theme Duplicated Names ---------------- ``` wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version')); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version')); ``` You can't call 2 stylesheets the same thing and expect it to work, which is what you've done with all 4 of your stylesheets Also notice that you've loaded `bootstrap.css` from both themes
289,342
<p>Where in the database can I find that a product is marked "featured"? I have marked 4 products as featured but I have yet to find out how to retrieve this information from any the database tables.</p> <p>Thank you.</p>
[ { "answer_id": 289322, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<h2>Parent vs Child Themes</h2>\n\n<p><code>get_template_directory_uri</code> always refers to the parent theme ...
2017/12/23
[ "https://wordpress.stackexchange.com/questions/289342", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131388/" ]
Where in the database can I find that a product is marked "featured"? I have marked 4 products as featured but I have yet to find out how to retrieve this information from any the database tables. Thank you.
Parent vs Child Themes ---------------------- `get_template_directory_uri` always refers to the parent theme you can verify this as you always should when things don't load as expected by looking in the console in the browsers dev tools. These would show 404 errors for the CSS files, in the wrong folder. Instead, use `get_stylesheet_directory_uri`, the `stylesheet` family of functions always refer to the current active theme Duplicated Names ---------------- ``` wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version')); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version')); ``` You can't call 2 stylesheets the same thing and expect it to work, which is what you've done with all 4 of your stylesheets Also notice that you've loaded `bootstrap.css` from both themes
289,349
<p>Is there a way to globally change the font size for Heading 1, Heading 2, Heading 3, etc. So, for example, if I want to change the font size for everything tagged with H2, every H2 text size on every page in the site changes.</p> <p>Thank you.</p>
[ { "answer_id": 289356, "author": "Arsalan Mithani", "author_id": 111402, "author_profile": "https://wordpress.stackexchange.com/users/111402", "pm_score": 1, "selected": false, "text": "<p>Depends on the theme you are using, some themes have general settings panel labelled as <strong>The...
2017/12/23
[ "https://wordpress.stackexchange.com/questions/289349", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132968/" ]
Is there a way to globally change the font size for Heading 1, Heading 2, Heading 3, etc. So, for example, if I want to change the font size for everything tagged with H2, every H2 text size on every page in the site changes. Thank you.
Sure, locate the style.css file within your theme and paste the code below. I suggest using percentages in your declarations so as to keep the base size styling hopefully already in your theme. ``` h1 { font-size: 150%; } h2 { font-size: 140%; } h3 { font-size: 130%; } h4 { font-size: 120%; } h5 { font-size: 110%; } ```
289,387
<p>how can I remove default pagination on woocommerce shop page ? and then use my custom pagination (or use pagination plugin) on woocommerce shop page</p> <p>thank you</p>
[ { "answer_id": 289565, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 2, "selected": false, "text": "<p>You need to locate the right file in the plugins/woocommerce/templates directory and make a woocommerce dire...
2017/12/24
[ "https://wordpress.stackexchange.com/questions/289387", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131388/" ]
how can I remove default pagination on woocommerce shop page ? and then use my custom pagination (or use pagination plugin) on woocommerce shop page thank you
I found the answer : 1) remove woocommerce pagination in theme functions.php : ``` remove_action( 'woocommerce_before_shop_loop', 'storefront_woocommerce_pagination', 30 ); ``` [storefront woocommerce template hooks](https://github.com/woocommerce/storefront/blob/8c510114a14f622e2219178a47c7da6d11556cb7/inc/woocommerce/storefront-woocommerce-template-hooks.php) 2) use the below code for customize your pagination in functions.php : ``` function bittersweet_pagination() { global $wp_query; $big = 999999999; // need an unlikely integer $pages = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'type' => 'array', ) ); if( is_array( $pages ) ) { $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged'); echo '<div class="pagination-wrap"><ul class="pagination">'; foreach ( $pages as $page ) { echo "<li>$page</li>"; } echo '</ul></div>'; } } ```
289,399
<p>hi i need your help regarding for woo-commerce product title based search we have list of product my searching keyword available in product title need to show list product. if product title don't have my search keyword but available in product description section this don't need to display this product. </p>
[ { "answer_id": 289565, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 2, "selected": false, "text": "<p>You need to locate the right file in the plugins/woocommerce/templates directory and make a woocommerce dire...
2017/12/24
[ "https://wordpress.stackexchange.com/questions/289399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114102/" ]
hi i need your help regarding for woo-commerce product title based search we have list of product my searching keyword available in product title need to show list product. if product title don't have my search keyword but available in product description section this don't need to display this product.
I found the answer : 1) remove woocommerce pagination in theme functions.php : ``` remove_action( 'woocommerce_before_shop_loop', 'storefront_woocommerce_pagination', 30 ); ``` [storefront woocommerce template hooks](https://github.com/woocommerce/storefront/blob/8c510114a14f622e2219178a47c7da6d11556cb7/inc/woocommerce/storefront-woocommerce-template-hooks.php) 2) use the below code for customize your pagination in functions.php : ``` function bittersweet_pagination() { global $wp_query; $big = 999999999; // need an unlikely integer $pages = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'type' => 'array', ) ); if( is_array( $pages ) ) { $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged'); echo '<div class="pagination-wrap"><ul class="pagination">'; foreach ( $pages as $page ) { echo "<li>$page</li>"; } echo '</ul></div>'; } } ```
289,421
<p>While writing a custom element for WC Bakery (formerly Visual Composer) I've discovered that the HTML tags are being stripped from the <code>textfield</code> parameter type. It's sanitizing the <code>textfield</code> value by default. </p> <p>I could not find a way to disable the <code>textfield</code> sanitization. </p> <p>How can I allow HTML tags to be entered into this field?</p>
[ { "answer_id": 315493, "author": "rtpHarry", "author_id": 60500, "author_profile": "https://wordpress.stackexchange.com/users/60500", "pm_score": 2, "selected": false, "text": "<p>You need to change the type from <code>textarea</code> to <code>textarea_raw_html</code>:</p>\n\n<ul>\n<li><...
2017/12/25
[ "https://wordpress.stackexchange.com/questions/289421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75264/" ]
While writing a custom element for WC Bakery (formerly Visual Composer) I've discovered that the HTML tags are being stripped from the `textfield` parameter type. It's sanitizing the `textfield` value by default. I could not find a way to disable the `textfield` sanitization. How can I allow HTML tags to be entered into this field?
You need to change the type from `textarea` to `textarea_raw_html`: * <https://kb.wpbakery.com/docs/inner-api/vc_map/> Under the section "Available type values" it says: > > textarea\_raw\_html: Text area, its content will be coded into base64 (this allows you to store raw js or raw html code) > > > Although I'm not sure why they can base64 encode the output from this but not the `textarea_html` box with its nice formatting - an annoying limitation. **UPDATE** It looks like you have to jump through some hoops when you switch to the `textarea_raw_html` param type. To use the value you need to manually decode it with: ``` $atts['some_param'] = rawurldecode( base64_decode( $atts['some_param'] ) ); ```
289,435
<p>I'd like to move all my assets (CSS, JS, Images, Fonts) in an asset folder in my theme.</p> <p>I did it very well for the fonts and images. For the CSS, I just kept the style.css with the style meta information in it (as advised <a href="https://wordpress.stackexchange.com/a/111505/133812">here</a>).</p> <p>But I'm using the great underscores.me starter theme for Wordpress and I have in my theme a JS folder containing customizer, navigation.js and skip-link-focus-fix.js</p> <p>All these scripts are included in my footer via the wp_footer() function. So, if I move these scripts to my /assets/js/ folder, I have three missing files called in the footer.</p> <p>Is there a way to (1) not load these scripts or (2) change the directory and tell the wp_footer to call /assets/js and not /js/ ?</p> <p>Thank you for your help.</p>
[ { "answer_id": 289441, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 2, "selected": true, "text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>...
2017/12/25
[ "https://wordpress.stackexchange.com/questions/289435", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133812/" ]
I'd like to move all my assets (CSS, JS, Images, Fonts) in an asset folder in my theme. I did it very well for the fonts and images. For the CSS, I just kept the style.css with the style meta information in it (as advised [here](https://wordpress.stackexchange.com/a/111505/133812)). But I'm using the great underscores.me starter theme for Wordpress and I have in my theme a JS folder containing customizer, navigation.js and skip-link-focus-fix.js All these scripts are included in my footer via the wp\_footer() function. So, if I move these scripts to my /assets/js/ folder, I have three missing files called in the footer. Is there a way to (1) not load these scripts or (2) change the directory and tell the wp\_footer to call /assets/js and not /js/ ? Thank you for your help.
go to your themes `functions.php` and find line 122. You will find navigation.js function. ``` get_template_directory_uri() . '/js/navigation.js ``` and change it to ``` get_template_directory_uri() . 'assets/js/navigation.js ``` do it again for `skip-link-focus-fix.js` code located on line 124. For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js` Don't forget to move your files :)
289,462
<p>So i came to three posible solutions to this question and can't decide which is better. What is your opinion?</p> <p>First solution:</p> <pre><code>if ( ( in_array('administrator', userdata('role')) || in_array('editor', userdata('role')) ) == false) { add_filter('show_admin_bar', '__return_false'); } </code></pre> <p>Second one:</p> <pre><code>if( ( current_user_can('editor') || current_user_can('administrator') ) == false ) { add_filter('show_admin_bar', '__return_false'); } </code></pre> <p>Third one:</p> <pre><code>$allowed_roles = array('editor', 'administrator'); if( array_intersect($allowed_roles, userdata('role') ) == false ) { add_filter('show_admin_bar', '__return_false'); } </code></pre> <p>User data function:</p> <pre><code>function userdata($userdata){ $userinfo = wp_get_current_user(); if ($userdata == 'nick') return $userinfo -&gt;user_login; if ($userdata == 'mail') return $userinfo -&gt;user_email; if ($userdata == 'id') return $userinfo -&gt;ID; if ($userdata == 'role') return $userinfo -&gt;roles; else return 'Eror'; } </code></pre> <p>I am voting for the third solution.</p>
[ { "answer_id": 289441, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 2, "selected": true, "text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>...
2017/12/25
[ "https://wordpress.stackexchange.com/questions/289462", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133829/" ]
So i came to three posible solutions to this question and can't decide which is better. What is your opinion? First solution: ``` if ( ( in_array('administrator', userdata('role')) || in_array('editor', userdata('role')) ) == false) { add_filter('show_admin_bar', '__return_false'); } ``` Second one: ``` if( ( current_user_can('editor') || current_user_can('administrator') ) == false ) { add_filter('show_admin_bar', '__return_false'); } ``` Third one: ``` $allowed_roles = array('editor', 'administrator'); if( array_intersect($allowed_roles, userdata('role') ) == false ) { add_filter('show_admin_bar', '__return_false'); } ``` User data function: ``` function userdata($userdata){ $userinfo = wp_get_current_user(); if ($userdata == 'nick') return $userinfo ->user_login; if ($userdata == 'mail') return $userinfo ->user_email; if ($userdata == 'id') return $userinfo ->ID; if ($userdata == 'role') return $userinfo ->roles; else return 'Eror'; } ``` I am voting for the third solution.
go to your themes `functions.php` and find line 122. You will find navigation.js function. ``` get_template_directory_uri() . '/js/navigation.js ``` and change it to ``` get_template_directory_uri() . 'assets/js/navigation.js ``` do it again for `skip-link-focus-fix.js` code located on line 124. For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js` Don't forget to move your files :)
289,474
<p>Whenever I post a new post or page, the website serves a 301 redirect to the homepage. All existing posts are working correctly (not redirecting). </p> <p>What I've tried:<br> - Checked console and confirm APACHE is serving 301<br> - Tried to re-save permalinks from Wordpress<br> - Checked .htaccess for anything out of the ordinary </p> <p>The problem was cause by previous developers and I'm unable to trace their work. </p> <p>Any help is appreciated, thanks.</p>
[ { "answer_id": 289441, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 2, "selected": true, "text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>...
2017/12/26
[ "https://wordpress.stackexchange.com/questions/289474", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133834/" ]
Whenever I post a new post or page, the website serves a 301 redirect to the homepage. All existing posts are working correctly (not redirecting). What I've tried: - Checked console and confirm APACHE is serving 301 - Tried to re-save permalinks from Wordpress - Checked .htaccess for anything out of the ordinary The problem was cause by previous developers and I'm unable to trace their work. Any help is appreciated, thanks.
go to your themes `functions.php` and find line 122. You will find navigation.js function. ``` get_template_directory_uri() . '/js/navigation.js ``` and change it to ``` get_template_directory_uri() . 'assets/js/navigation.js ``` do it again for `skip-link-focus-fix.js` code located on line 124. For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js` Don't forget to move your files :)
289,516
<p>I need to add a bus timings category for a client.</p> <p>I need to have </p> <p>FROM STOP (selectable field) TO STOP (selectable field) START HOUR (selectable field but optional) END HOUR (selectable field but optional)</p> <p>take these inputs and show results with running buses in table within those times.</p> <p>similar to this one </p> <p>stackoverflow.com/questions/40524279/need-mysql-query-for-search-bus-from-stop-and-to-stop</p> <p>Which do i use CPT or meta fields ?</p> <p>Kindly help me get started.</p>
[ { "answer_id": 289441, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 2, "selected": true, "text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>...
2017/12/26
[ "https://wordpress.stackexchange.com/questions/289516", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133860/" ]
I need to add a bus timings category for a client. I need to have FROM STOP (selectable field) TO STOP (selectable field) START HOUR (selectable field but optional) END HOUR (selectable field but optional) take these inputs and show results with running buses in table within those times. similar to this one stackoverflow.com/questions/40524279/need-mysql-query-for-search-bus-from-stop-and-to-stop Which do i use CPT or meta fields ? Kindly help me get started.
go to your themes `functions.php` and find line 122. You will find navigation.js function. ``` get_template_directory_uri() . '/js/navigation.js ``` and change it to ``` get_template_directory_uri() . 'assets/js/navigation.js ``` do it again for `skip-link-focus-fix.js` code located on line 124. For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js` Don't forget to move your files :)
289,520
<p>I am tasked with updating plugins and core on a number of blogs that I am completely unfamiliar with (nothing weird about them, but I haven't worked with them before today). </p> <p>What I need to do is update all the plugins and the core, and after it's done fix or rollback any introduced bugs. Thing is, I don't have shell access and I don't have access to a home directory on the server, so I can't automate a lot, or I don't know how to automate anything that will run tests or the like after every update to make sure that nothing is broken.</p> <p>These are fairly large sites, so there are a lot of places bugs can hide. Is there a recommended procedure for this? Or is there a way that I can pretty well reliably catch any new bugs introduced? </p> <p>I'm not worried about temporary errors, because this is a staging environment, but I do want comprehensive knowledge that nothing is busted. I should have access to error_log files, but I'm not 100% sure I do yet, and I haven't seen any.</p> <p>Any help?</p>
[ { "answer_id": 289441, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 2, "selected": true, "text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>...
2017/12/26
[ "https://wordpress.stackexchange.com/questions/289520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65569/" ]
I am tasked with updating plugins and core on a number of blogs that I am completely unfamiliar with (nothing weird about them, but I haven't worked with them before today). What I need to do is update all the plugins and the core, and after it's done fix or rollback any introduced bugs. Thing is, I don't have shell access and I don't have access to a home directory on the server, so I can't automate a lot, or I don't know how to automate anything that will run tests or the like after every update to make sure that nothing is broken. These are fairly large sites, so there are a lot of places bugs can hide. Is there a recommended procedure for this? Or is there a way that I can pretty well reliably catch any new bugs introduced? I'm not worried about temporary errors, because this is a staging environment, but I do want comprehensive knowledge that nothing is busted. I should have access to error\_log files, but I'm not 100% sure I do yet, and I haven't seen any. Any help?
go to your themes `functions.php` and find line 122. You will find navigation.js function. ``` get_template_directory_uri() . '/js/navigation.js ``` and change it to ``` get_template_directory_uri() . 'assets/js/navigation.js ``` do it again for `skip-link-focus-fix.js` code located on line 124. For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js` Don't forget to move your files :)
289,556
<p>I have id of WP category on external resource. I know that if I have id of post I can create url like</p> <blockquote> <p><a href="http://example.com/?p=" rel="nofollow noreferrer">http://example.com/?p=</a>{post_id}</p> </blockquote> <p>But what if I know id of category? How can I generate link to it? Category permalinks look like</p> <blockquote> <p><a href="http://example.com/category/" rel="nofollow noreferrer">http://example.com/category/</a>{category_slug}/</p> </blockquote> <p>and I need to use something like</p> <blockquote> <p><a href="http://example.com/category/?cat_id=" rel="nofollow noreferrer">http://example.com/category/?cat_id=</a>{category_id}/</p> </blockquote>
[ { "answer_id": 289557, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"...
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289556", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16650/" ]
I have id of WP category on external resource. I know that if I have id of post I can create url like > > <http://example.com/?p=>{post\_id} > > > But what if I know id of category? How can I generate link to it? Category permalinks look like > > <http://example.com/category/>{category\_slug}/ > > > and I need to use something like > > <http://example.com/category/?cat_id=>{category\_id}/ > > >
If you have category ID you can create link to category like below : ``` <a href="/index.php?cat=7">Category Title</a> ``` For more details read from this link : <https://codex.wordpress.org/Linking_Posts_Pages_and_Categories> Thanks!
289,558
<p>I have recently enabled SSL certificate and I'm tring to use it in my wordpress site. My website's url is </p> <hr> <p>All plugings are disabled.</p> <hr> <p>I replaced </p> <pre><code> define('WP_HOME','http://mywebsite.com'); define('WP_SITEURL','http://mywebsite.com'); </code></pre> <p>with:</p> <pre><code>define('WP_HOME','https://mywebsite.com'); define('WP_SITEURL','https://mywebsite.com'); </code></pre> <hr> <p>Here's what I get in <a href="http://www.redirect-checker.org" rel="nofollow noreferrer">http://www.redirect-checker.org</a>:</p> <blockquote> <p>301 Moved Permanently <a href="https://mywebsite.com/" rel="nofollow noreferrer">https://mywebsite.com/</a> 301 Moved Permanently <a href="https://mywebsite.com/" rel="nofollow noreferrer">https://mywebsite.com/</a> 301 Moved Permanently <a href="https://mywebsite.com/" rel="nofollow noreferrer">https://mywebsite.com/</a> 301 Moved Permanently</p> <p>Problems found: Too many redirects. Please try to reduce your number of redirects for <a href="https://mywebsite.com" rel="nofollow noreferrer">https://mywebsite.com</a>. Actually you use 19 Redirects. Ideally you should not use more than 3 Redirects in a redirect chain. More than 3 redirections will produce unnecessary load on your server and reduces speed, which ends up in bad user experience.</p> </blockquote> <hr> <p>A simple .txt file is working ok with https. For example:</p> <p><strong><a href="https://mywebsite.com/license.txt" rel="nofollow noreferrer">https://mywebsite.com/license.txt</a></strong></p> <p>gives "200 OK" message and page is browsed via https normally.</p> <p>But trying to browse .index.php (which includes wordpress) is giving "too many redirects" error.</p> <hr> <p>I tried adding redirects to .htacess file but didn't work. I have read many articles about this issu but haven't managed to solve it. Can you help me please?</p> <hr> <p>UPDATE</p> <p>Here are the _SERVER variables, shown by phpinfo()</p> <pre><code>_SERVER["UNIQUE_ID"] WkOCLwoADAIAAFpxjJQAAAAG _SERVER["QS_SrvConn"] 290 _SERVER["QS_AllConn"] 290 _SERVER["QS_ConnectionId"] 15143736798377620623491 _SERVER["HTTPS"] 1 _SERVER["HOME"] /home10a/sub002/sc11808-TCBG _SERVER["HTTP_HOST"] mywebsite.com _SERVER["HTTP_USER_AGENT"] Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36 _SERVER["HTTP_UPGRADE_INSECURE_REQUESTS"] 1 _SERVER["HTTP_ACCEPT"] text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 _SERVER["HTTP_ACCEPT_ENCODING"] gzip, deflate, br _SERVER["HTTP_ACCEPT_LANGUAGE"] en-US,en;q=0.9,el;q=0.8 _SERVER["HTTP_COOKIE"] wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_dbdaedf581c00cfca1e0c4de7c421d21=marketing%7C1514545975%7C91BD7fgU1i2AZl6rYQQ1cjIFfYkG2raYJp0VNXAIEHM%7C9a9f559abd4e30c57834d12a093683a1b6ff5dff14fbbf341983e1acee2fef58; wp-settings-3=mfold%3Do%26editor%3Dtinymce%26libraryContent%3Dbrowse%26galleryitemtype_tab%3Dpop%26hidetb%3D1%26wplink%3D0%26posts_list_mode%3Dlist%26imgsize%3Dfull; wp-settings-time-3=1514373177; redux_blast=1514373287; PHPSESSID=568be9d8e51767786dfc80915ff881a3; redux_update_check=3.6.7.13 _SERVER["HTTP_SSL"] on _SERVER["HTTP_X_FORWARDED_FOR"] 78.108.43.18 _SERVER["HTTP_X_FORWARDED_HOST"] mywebsite.com _SERVER["HTTP_X_FORWARDED_SERVER"] mywebsite.com _SERVER["PATH"] /usr/local/bin:/usr/bin:/bin _SERVER["SERVER_SIGNATURE"] &lt;address&gt;Apache Server at mywebsite.com Port 80&lt;/address&gt; _SERVER["SERVER_SOFTWARE"] Apache _SERVER["SERVER_NAME"] mywebsite.com _SERVER["SERVER_ADDR"] 10.0.12.2 _SERVER["SERVER_PORT"] 80 _SERVER["REMOTE_ADDR"] 77.232.66.255 _SERVER["DOCUMENT_ROOT"] /home10a/sub002/sc11808-TCBG/www _SERVER["SERVER_ADMIN"] [no address given] _SERVER["SCRIPT_FILENAME"] /home10a/sub002/sc11808-TCBG/www/info.php _SERVER["REMOTE_PORT"] 45245 _SERVER["GATEWAY_INTERFACE"] CGI/1.1 _SERVER["SERVER_PROTOCOL"] HTTP/1.0 _SERVER["REQUEST_METHOD"] GET _SERVER["QUERY_STRING"] no value _SERVER["REQUEST_URI"] /info.php _SERVER["SCRIPT_NAME"] /info.php _SERVER["PHP_SELF"] /info.php _SERVER["REQUEST_TIME"] 1514373679 </code></pre> <hr>
[ { "answer_id": 289557, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"...
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16847/" ]
I have recently enabled SSL certificate and I'm tring to use it in my wordpress site. My website's url is --- All plugings are disabled. --- I replaced ``` define('WP_HOME','http://mywebsite.com'); define('WP_SITEURL','http://mywebsite.com'); ``` with: ``` define('WP_HOME','https://mywebsite.com'); define('WP_SITEURL','https://mywebsite.com'); ``` --- Here's what I get in <http://www.redirect-checker.org>: > > 301 Moved Permanently <https://mywebsite.com/> 301 Moved Permanently > <https://mywebsite.com/> 301 Moved Permanently <https://mywebsite.com/> 301 > Moved Permanently > > > Problems found: Too many redirects. Please try to reduce your number > of redirects for <https://mywebsite.com>. Actually you use 19 Redirects. > Ideally you should not use more than 3 Redirects in a redirect chain. > More than 3 redirections will produce unnecessary load on your server > and reduces speed, which ends up in bad user experience. > > > --- A simple .txt file is working ok with https. For example: **<https://mywebsite.com/license.txt>** gives "200 OK" message and page is browsed via https normally. But trying to browse .index.php (which includes wordpress) is giving "too many redirects" error. --- I tried adding redirects to .htacess file but didn't work. I have read many articles about this issu but haven't managed to solve it. Can you help me please? --- UPDATE Here are the \_SERVER variables, shown by phpinfo() ``` _SERVER["UNIQUE_ID"] WkOCLwoADAIAAFpxjJQAAAAG _SERVER["QS_SrvConn"] 290 _SERVER["QS_AllConn"] 290 _SERVER["QS_ConnectionId"] 15143736798377620623491 _SERVER["HTTPS"] 1 _SERVER["HOME"] /home10a/sub002/sc11808-TCBG _SERVER["HTTP_HOST"] mywebsite.com _SERVER["HTTP_USER_AGENT"] Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36 _SERVER["HTTP_UPGRADE_INSECURE_REQUESTS"] 1 _SERVER["HTTP_ACCEPT"] text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 _SERVER["HTTP_ACCEPT_ENCODING"] gzip, deflate, br _SERVER["HTTP_ACCEPT_LANGUAGE"] en-US,en;q=0.9,el;q=0.8 _SERVER["HTTP_COOKIE"] wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_dbdaedf581c00cfca1e0c4de7c421d21=marketing%7C1514545975%7C91BD7fgU1i2AZl6rYQQ1cjIFfYkG2raYJp0VNXAIEHM%7C9a9f559abd4e30c57834d12a093683a1b6ff5dff14fbbf341983e1acee2fef58; wp-settings-3=mfold%3Do%26editor%3Dtinymce%26libraryContent%3Dbrowse%26galleryitemtype_tab%3Dpop%26hidetb%3D1%26wplink%3D0%26posts_list_mode%3Dlist%26imgsize%3Dfull; wp-settings-time-3=1514373177; redux_blast=1514373287; PHPSESSID=568be9d8e51767786dfc80915ff881a3; redux_update_check=3.6.7.13 _SERVER["HTTP_SSL"] on _SERVER["HTTP_X_FORWARDED_FOR"] 78.108.43.18 _SERVER["HTTP_X_FORWARDED_HOST"] mywebsite.com _SERVER["HTTP_X_FORWARDED_SERVER"] mywebsite.com _SERVER["PATH"] /usr/local/bin:/usr/bin:/bin _SERVER["SERVER_SIGNATURE"] <address>Apache Server at mywebsite.com Port 80</address> _SERVER["SERVER_SOFTWARE"] Apache _SERVER["SERVER_NAME"] mywebsite.com _SERVER["SERVER_ADDR"] 10.0.12.2 _SERVER["SERVER_PORT"] 80 _SERVER["REMOTE_ADDR"] 77.232.66.255 _SERVER["DOCUMENT_ROOT"] /home10a/sub002/sc11808-TCBG/www _SERVER["SERVER_ADMIN"] [no address given] _SERVER["SCRIPT_FILENAME"] /home10a/sub002/sc11808-TCBG/www/info.php _SERVER["REMOTE_PORT"] 45245 _SERVER["GATEWAY_INTERFACE"] CGI/1.1 _SERVER["SERVER_PROTOCOL"] HTTP/1.0 _SERVER["REQUEST_METHOD"] GET _SERVER["QUERY_STRING"] no value _SERVER["REQUEST_URI"] /info.php _SERVER["SCRIPT_NAME"] /info.php _SERVER["PHP_SELF"] /info.php _SERVER["REQUEST_TIME"] 1514373679 ``` ---
If you have category ID you can create link to category like below : ``` <a href="/index.php?cat=7">Category Title</a> ``` For more details read from this link : <https://codex.wordpress.org/Linking_Posts_Pages_and_Categories> Thanks!
289,574
<p>This is my entire code and it is working perfectly in my local system xampp but not working on server.</p> <pre><code>function taqyeem_dequeue_scrips() { if(basename($_SERVER['REQUEST_URI'])=='my_page' || basename($_SERVER['REQUEST_URI'])=='') { wp_dequeue_style( 'taqyeem-style' ); wp_dequeue_script( 'taqyeem-main' ); wp_deregister_script( 'comment-reply' ); } } add_action( 'init', 'taqyeem_dequeue_scrips' ); function dequeue_scrips() { if(basename($_SERVER['REQUEST_URI'])=='my_page') { //css wp_dequeue_style( 'taxonomy-image-plugin-public' ); wp_dequeue_style( 'job-alerts-frontend' ); wp_dequeue_style('validate-engine-css'); wp_dequeue_style('cp-shortcode'); wp_dequeue_style('wsl-widget'); wp_dequeue_style('wp-job-manager-applications-frontend'); wp_dequeue_style('wp-job-manager-bookmarks-frontend'); wp_dequeue_style('wp-job-manager-resume-frontend'); wp_dequeue_style('wp-job-manager-frontend'); wp_dequeue_style('cp-widgets-css'); wp_dequeue_style('responsive-css'); wp_dequeue_style('owl-css'); wp_dequeue_style('svg-css'); wp_dequeue_style('cp-burgermenucss'); wp_dequeue_style('law-bx-slider-css'); wp_dequeue_style('prettyPhoto'); wp_dequeue_style('cp-bootstrap'); wp_dequeue_style('cp-wp-commerce'); wp_dequeue_style('cp-bx-slider'); wp_dequeue_style('googleFonts'); wp_dequeue_style('googleFonts-heading'); wp_dequeue_style('menu-googleFonts-heading'); wp_dequeue_style('wppb_stylesheet'); wp_dequeue_style('A2A_SHARE_SAVE'); //Script wp_dequeue_script( 'html5shiv' ); wp_dequeue_script( 'cp-bootstrap' ); wp_dequeue_script( 'addtoany' ); wp_dequeue_script( 'cp-owl-js' ); wp_dequeue_script( 'cp-velocity' ); wp_dequeue_script( 'owl-kenburns' ); wp_dequeue_script( 'cp-burgermenu' ); wp_dequeue_script( 'cp-burgermenucustom' ); wp_dequeue_script( 'cp-bx-slider' ); wp_dequeue_script( 'cp-custom' ); wp_dequeue_script( 'prettyPhoto' ); wp_dequeue_script( 'cp-pscript' ); wp_dequeue_script( 'cp-scripts_modernizr' ); wp_dequeue_script( 'cp-scripts' ); wp_dequeue_script( 'cp-scripts-workmark' ); wp_dequeue_script( 'cp-easing' ); wp_dequeue_script( 'cp-bx-slider' ); } } add_action( 'wp_enqueue_scripts', 'dequeue_scrips' ); </code></pre> <p>Any suggestion please. I am working to improve Google Page Speed to get atleast 90 score in mobile and desktop. Currently itis poor in mobile (56 )</p>
[ { "answer_id": 289557, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"...
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70096/" ]
This is my entire code and it is working perfectly in my local system xampp but not working on server. ``` function taqyeem_dequeue_scrips() { if(basename($_SERVER['REQUEST_URI'])=='my_page' || basename($_SERVER['REQUEST_URI'])=='') { wp_dequeue_style( 'taqyeem-style' ); wp_dequeue_script( 'taqyeem-main' ); wp_deregister_script( 'comment-reply' ); } } add_action( 'init', 'taqyeem_dequeue_scrips' ); function dequeue_scrips() { if(basename($_SERVER['REQUEST_URI'])=='my_page') { //css wp_dequeue_style( 'taxonomy-image-plugin-public' ); wp_dequeue_style( 'job-alerts-frontend' ); wp_dequeue_style('validate-engine-css'); wp_dequeue_style('cp-shortcode'); wp_dequeue_style('wsl-widget'); wp_dequeue_style('wp-job-manager-applications-frontend'); wp_dequeue_style('wp-job-manager-bookmarks-frontend'); wp_dequeue_style('wp-job-manager-resume-frontend'); wp_dequeue_style('wp-job-manager-frontend'); wp_dequeue_style('cp-widgets-css'); wp_dequeue_style('responsive-css'); wp_dequeue_style('owl-css'); wp_dequeue_style('svg-css'); wp_dequeue_style('cp-burgermenucss'); wp_dequeue_style('law-bx-slider-css'); wp_dequeue_style('prettyPhoto'); wp_dequeue_style('cp-bootstrap'); wp_dequeue_style('cp-wp-commerce'); wp_dequeue_style('cp-bx-slider'); wp_dequeue_style('googleFonts'); wp_dequeue_style('googleFonts-heading'); wp_dequeue_style('menu-googleFonts-heading'); wp_dequeue_style('wppb_stylesheet'); wp_dequeue_style('A2A_SHARE_SAVE'); //Script wp_dequeue_script( 'html5shiv' ); wp_dequeue_script( 'cp-bootstrap' ); wp_dequeue_script( 'addtoany' ); wp_dequeue_script( 'cp-owl-js' ); wp_dequeue_script( 'cp-velocity' ); wp_dequeue_script( 'owl-kenburns' ); wp_dequeue_script( 'cp-burgermenu' ); wp_dequeue_script( 'cp-burgermenucustom' ); wp_dequeue_script( 'cp-bx-slider' ); wp_dequeue_script( 'cp-custom' ); wp_dequeue_script( 'prettyPhoto' ); wp_dequeue_script( 'cp-pscript' ); wp_dequeue_script( 'cp-scripts_modernizr' ); wp_dequeue_script( 'cp-scripts' ); wp_dequeue_script( 'cp-scripts-workmark' ); wp_dequeue_script( 'cp-easing' ); wp_dequeue_script( 'cp-bx-slider' ); } } add_action( 'wp_enqueue_scripts', 'dequeue_scrips' ); ``` Any suggestion please. I am working to improve Google Page Speed to get atleast 90 score in mobile and desktop. Currently itis poor in mobile (56 )
If you have category ID you can create link to category like below : ``` <a href="/index.php?cat=7">Category Title</a> ``` For more details read from this link : <https://codex.wordpress.org/Linking_Posts_Pages_and_Categories> Thanks!
289,582
<p>I need to remove trailing slash from URLs ending with <code>.xml/</code> only .. For this purpose I've created a Rewrite Condition and Rule which is working perfectly fine for the test link <a href="http://website.com/test.xml/" rel="nofollow noreferrer">http://website.com/test.xml/</a></p> <p>Test Link: <a href="http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f" rel="nofollow noreferrer">http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f</a></p> <p>The problem is when I place the rule in WordPress <code>.htaccess</code> file, it doesn't work at all! Seems like WordPress or YOAST Permalink structure is overriding the rule .. please help!</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_URI} /(.*).xml/$ RewriteRule ^ /%1.xml [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Note:</p> <p>Please note that this is not a physical file .. using rewrite rules to generate sitemap on the run! This is a wordpress page in fact!</p> <p><code>add_rewrite_rule('([^/]*)-placeholder.xml','index.php?page_id=123&amp;custom‌​-slug=$matches[1]','‌​top');</code></p>
[ { "answer_id": 289588, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<blockquote>\n<pre><code>RewriteRule ^ /%1.xml [L]\n</code></pre>\n</blockquote>\n\n<p>This should be an <em>exter...
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58627/" ]
I need to remove trailing slash from URLs ending with `.xml/` only .. For this purpose I've created a Rewrite Condition and Rule which is working perfectly fine for the test link <http://website.com/test.xml/> Test Link: <http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f> The problem is when I place the rule in WordPress `.htaccess` file, it doesn't work at all! Seems like WordPress or YOAST Permalink structure is overriding the rule .. please help! ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_URI} /(.*).xml/$ RewriteRule ^ /%1.xml [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` Note: Please note that this is not a physical file .. using rewrite rules to generate sitemap on the run! This is a wordpress page in fact! `add_rewrite_rule('([^/]*)-placeholder.xml','index.php?page_id=123&custom‌​-slug=$matches[1]','‌​top');`
What exactly worked out for me .. The issue was due to WordPress canonical redirects .. The use of `/%postname%/` in permalink structure was redirecting the custom template to the trailing slash URL. I simply removed the `template_redirect` filter for canonical redirects .. and now the link works in both cases i.e. with or without trailing slash. Here is my code for reference.. 1234 is the example page id for the template used to generate dynamic sitemap. `//Disabling canonical redirects for sitemap function disable_sitemap_redirect() { global $wp; $current_url = home_url(add_query_arg(array(),$wp->request)); $current_url = $current_url . $_SERVER['REDIRECT_URL']; $id = url_to_postid($current_url); if($id == 1234) : remove_filter('template_redirect', 'redirect_canonical'); endif; } add_action('init', 'disable_sitemap_redirect', 10, 0);`
289,590
<p>im new with wordpress. im planning to connect wordpress database from my own php code . but i get problem when trying to connect database, everytime i connect always get error result. im using this code</p> <pre><code>$user_name = "myusername"; $password = "password"; $database = "mydatabasename"; $host_name = "localhost"; $connect_db=mysqli_connect($host_name, $user_name, $password); $find_db=mysqli_select_db($database); if ($find_db) { echo "Database found"; mysqli_close($connect_db); } else { echo "Database notfound"; mysqli_close($connect_db); } </code></pre>
[ { "answer_id": 289594, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>....
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289590", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133890/" ]
im new with wordpress. im planning to connect wordpress database from my own php code . but i get problem when trying to connect database, everytime i connect always get error result. im using this code ``` $user_name = "myusername"; $password = "password"; $database = "mydatabasename"; $host_name = "localhost"; $connect_db=mysqli_connect($host_name, $user_name, $password); $find_db=mysqli_select_db($database); if ($find_db) { echo "Database found"; mysqli_close($connect_db); } else { echo "Database notfound"; mysqli_close($connect_db); } ```
While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code). By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information. First you need to link to the Wordpress class: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); ``` If you get an error, check that the path to wp-load is correct and adjust if necessary. Next you can define the user and database etc. ``` /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); ``` This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below: ``` $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); ``` Finally you can do something with the results for example: ``` $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` Putting it all together your code would look like this: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' ); define('SHORTINIT', true ); /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` The additional SHORTINIT definition is added to minimise the Wordpress load but is not required. I hope that this helps.
289,600
<p>Since I'm pretty new to WordPress, I would like to know what is the right way to edit the WP reset password email. I would like to change the message.</p> <p>I see that I need to edit the <code>retrieve_password_message</code> filter but I cannot understand if I can change the <code>wp-login.php</code> file.</p> <p>What will happen in case of WP update? Thanks</p>
[ { "answer_id": 289594, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>....
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133892/" ]
Since I'm pretty new to WordPress, I would like to know what is the right way to edit the WP reset password email. I would like to change the message. I see that I need to edit the `retrieve_password_message` filter but I cannot understand if I can change the `wp-login.php` file. What will happen in case of WP update? Thanks
While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code). By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information. First you need to link to the Wordpress class: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); ``` If you get an error, check that the path to wp-load is correct and adjust if necessary. Next you can define the user and database etc. ``` /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); ``` This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below: ``` $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); ``` Finally you can do something with the results for example: ``` $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` Putting it all together your code would look like this: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' ); define('SHORTINIT', true ); /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` The additional SHORTINIT definition is added to minimise the Wordpress load but is not required. I hope that this helps.
289,605
<p>In my Ubuntu VPS, to search and replace in a DB of a site I do for example:</p> <pre><code>cd /var/www/html/example.com sudo wp search-replace "http://" "https://" --all-tables </code></pre> <p>Yet in Windows 10 I use XAMPP and can't do this action with WSL + WP-CLI because one cannot use Bash inside windows (yet).</p> <h2>My problem</h2> <p>I have installed a backup version of an online website in Windows XAMPP and all main menu links turn to the online site so I need to change in DB from <code>https://</code> to <code>localhost://</code>.</p> <h2>My question</h2> <p>How could I easily and efficiently change the DB from <code>https://</code> to <code>localhost://</code>. in XAMPP in Windows?</p>
[ { "answer_id": 289594, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>....
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289605", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131001/" ]
In my Ubuntu VPS, to search and replace in a DB of a site I do for example: ``` cd /var/www/html/example.com sudo wp search-replace "http://" "https://" --all-tables ``` Yet in Windows 10 I use XAMPP and can't do this action with WSL + WP-CLI because one cannot use Bash inside windows (yet). My problem ---------- I have installed a backup version of an online website in Windows XAMPP and all main menu links turn to the online site so I need to change in DB from `https://` to `localhost://`. My question ----------- How could I easily and efficiently change the DB from `https://` to `localhost://`. in XAMPP in Windows?
While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code). By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information. First you need to link to the Wordpress class: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); ``` If you get an error, check that the path to wp-load is correct and adjust if necessary. Next you can define the user and database etc. ``` /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); ``` This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below: ``` $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); ``` Finally you can do something with the results for example: ``` $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` Putting it all together your code would look like this: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' ); define('SHORTINIT', true ); /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` The additional SHORTINIT definition is added to minimise the Wordpress load but is not required. I hope that this helps.
289,622
<p>I've looked through all the similar threads I can find, and I think I <em>should</em> have all the pieces in place to have translated strings appear, but they are not. I'm about ready to pull out my hair!</p> <p>Here's what I've got going - I'm making a custom theme (based on the _s starter), and I have added templates for some custom post types (created in my own plugins). I installed the Loco Translate plugin to create and edit po/mo files. The files are stored in 'mytheme/languages'.</p> <p>In my theme's functions.php I have:</p> <pre><code>/** * Load theme text domain for translations */ function mytheme_load_theme_textdomain() { if (load_theme_textdomain('mytheme', get_template_directory() . '/languages')) { error_log("Text Domain loaded."); } } add_action('after_setup_theme', 'mytheme_load_theme_textdomain'); </code></pre> <p>In my template part file, I have the strings set up for display like this:</p> <p><code>&lt;?php _e('My String Text', 'mytheme'); ?&gt;</code></p> <p>When I load the page that should have the translated strings, then look at the debug.log file, I see the message "Text Domain loaded." So that part should be working. Loco Translate correctly sees the strings and allows me to translate them. So everything in the .mo file should be correct.</p> <p>I have tried hardcoding the locale in wp-config.php (just to check) by adding <code>define('WPLANG', 'es_ES');</code> and echoing the global <code>$locale</code> variable to the debug log from within the function described above. That works correctly.</p> <p>Edit: adding output from debug-mo-translations plugin</p> <pre><code>Debug MO Translations (Version 1.0) Locale: es_ES Domain: mytheme File: /wp-content/languages/themes/mytheme-es_ES.mo (not found) Called in: /wp-includes/l10n.php line 792 load_textdomain Domain: mytheme File: /wp-content/languages/loco/themes/mytheme-es_ES.mo (not found) Called in: /wp-content/plugins/loco-translate/src/hooks/LoadHelper.php line 103 load_textdomain Domain: mytheme File: /wp-content/themes/mytheme/languages/es_ES.mo (0.62kb) Called in: /wp-includes/l10n.php line 800 load_textdomain </code></pre> <p>So, I've got translatable strings in my template file, I've got translations in .po/.mo files within my theme, the locale is correctly set, and I load my theme text domain in my functions.php file. But the strings still do not appear in translated form on the front end! What am I missing?</p> <p>Thanks in advance!</p>
[ { "answer_id": 289594, "author": "D. Dan", "author_id": 133528, "author_profile": "https://wordpress.stackexchange.com/users/133528", "pm_score": 0, "selected": false, "text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>....
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289622", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69989/" ]
I've looked through all the similar threads I can find, and I think I *should* have all the pieces in place to have translated strings appear, but they are not. I'm about ready to pull out my hair! Here's what I've got going - I'm making a custom theme (based on the \_s starter), and I have added templates for some custom post types (created in my own plugins). I installed the Loco Translate plugin to create and edit po/mo files. The files are stored in 'mytheme/languages'. In my theme's functions.php I have: ``` /** * Load theme text domain for translations */ function mytheme_load_theme_textdomain() { if (load_theme_textdomain('mytheme', get_template_directory() . '/languages')) { error_log("Text Domain loaded."); } } add_action('after_setup_theme', 'mytheme_load_theme_textdomain'); ``` In my template part file, I have the strings set up for display like this: `<?php _e('My String Text', 'mytheme'); ?>` When I load the page that should have the translated strings, then look at the debug.log file, I see the message "Text Domain loaded." So that part should be working. Loco Translate correctly sees the strings and allows me to translate them. So everything in the .mo file should be correct. I have tried hardcoding the locale in wp-config.php (just to check) by adding `define('WPLANG', 'es_ES');` and echoing the global `$locale` variable to the debug log from within the function described above. That works correctly. Edit: adding output from debug-mo-translations plugin ``` Debug MO Translations (Version 1.0) Locale: es_ES Domain: mytheme File: /wp-content/languages/themes/mytheme-es_ES.mo (not found) Called in: /wp-includes/l10n.php line 792 load_textdomain Domain: mytheme File: /wp-content/languages/loco/themes/mytheme-es_ES.mo (not found) Called in: /wp-content/plugins/loco-translate/src/hooks/LoadHelper.php line 103 load_textdomain Domain: mytheme File: /wp-content/themes/mytheme/languages/es_ES.mo (0.62kb) Called in: /wp-includes/l10n.php line 800 load_textdomain ``` So, I've got translatable strings in my template file, I've got translations in .po/.mo files within my theme, the locale is correctly set, and I load my theme text domain in my functions.php file. But the strings still do not appear in translated form on the front end! What am I missing? Thanks in advance!
While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code). By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information. First you need to link to the Wordpress class: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); ``` If you get an error, check that the path to wp-load is correct and adjust if necessary. Next you can define the user and database etc. ``` /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); ``` This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below: ``` $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); ``` Finally you can do something with the results for example: ``` $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` Putting it all together your code would look like this: ``` echo '<h1>WP Connect DB</h1>'; echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>'; require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' ); define('SHORTINIT', true ); /** The name of the database for WordPress */ define('DB_NAME', 'mydatabase'); /** MySQL database username */ define('DB_USER', 'myusername'); /** MySQL database password */ define('DB_PASSWORD', 'mypassword'); /** MySQL hostname */ define('DB_HOST', 'localhost'); $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $rows = $wpdb->get_results( "SELECT * FROM wp_posts" ); echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>'; ``` The additional SHORTINIT definition is added to minimise the Wordpress load but is not required. I hope that this helps.
289,623
<p>I need to remove some external .js files from source here is source: view-source:buhehe.de/ausmalbilder/ There is 3 jquery library and I don't know what is difference, why is it not one enough?</p> <pre><code>&lt;script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"&gt;&lt;/script&gt; </code></pre> <p>Can I leave only one?</p> <p>And how can I remove following:</p> <pre><code>&lt;script type='text/javascript' src='http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1'&gt;&lt;/script&gt; </code></pre>
[ { "answer_id": 289624, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>Firstly: Are you absolutely sure that you don't need them?</p>\n\n<p>Secondly: I'm assuming <code>s...
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289623", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133900/" ]
I need to remove some external .js files from source here is source: view-source:buhehe.de/ausmalbilder/ There is 3 jquery library and I don't know what is difference, why is it not one enough? ``` <script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script> <script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script> <script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"></script> ``` Can I leave only one? And how can I remove following: ``` <script type='text/javascript' src='http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1'></script> <script type='text/javascript' src='http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1'></script> ```
Firstly: Are you absolutely sure that you don't need them? Secondly: I'm assuming `small-menu.js` is for the mobile menu and `wp-embed.min.js` you want in case you use embeds. If I'm right, then you might want to keep the former. Aside from that you likely will find a `wp_enqueue_script` line for the former in your theme's `functions.php`. For the latter take a look at »[What does wp-embed.min.js do in WordPress 4.4?](https://wordpress.stackexchange.com/q/211701/22534)«. To keep it short and simple about the jQuery lines, WordPress loads `jquery.js` and `jquery-migrate.min.js` for compatibility reasons. I would suggest you keep it that way, unless you are really sure what you're doing. Additionally your theme loads another jQuery source, which generally isn't recommended. But there might be a reason to do so, so it can't be easily answered, if you simply can remove it. You'll likely find this one it the `functions.php` as a `wp_enqueue_script` line too.
289,634
<p>This is my code:</p> <pre><code>$args = array ( 'order' =&gt; 'DESC', 'include' =&gt; get_user_meta($author-&gt;ID, 'the_following_users', true) ); $wp_user_query = new WP_User_Query( $args ); $users = $wp_user_query-&gt;get_results(); if ( ! empty( $users ) ) { foreach ( $users as $user ) { // Get users } } else { echo 'Error.'; } </code></pre> <p>The user meta 'the_users' may be empty so if it's empty it's got to me all registered users if not empty it's print the users that I need.</p> <p>The problem that <code>if ( ! empty( $users ) ) { }</code> is not reading if 'include' is empty or not, I know I can make a variable and check first if the variable is empty or not but I don't need this I want to check if 'include' is empty by using '$wp_user_query->get_results()'.</p> <p><strong>EDIT:</strong></p> <p>As Nicolai answer we can replace true to false from get_user_meta code and the problem will be solved and if the include is empty the WP-User_Query will return a false and print error.</p> <p>The problem now that if include not empty so the code must be working without any issues but that does not happen it ignores the users that stored in 'the_users' user meta and print only current user.</p> <p>Here's the value of 'the_users' user meta:</p> <pre><code>a:19:{i:0;s:2:"89";i:3;s:3:"105";i:4;s:2:"74";i:5;s:3:"111";i:6;s:3:"167";i:7;s:2:"83";i:8;s:2:"54";i:9;s:2:"87";i:10;s:2:"85";i:11;s:2:"77";i:13;s:2:"82";i:14;s:2:"60";i:15;s:3:"149";i:16;s:3:"160";i:17;s:2:"71";i:18;s:1:"3";i:19;s:1:"2";i:20;s:3:"121";i:21;s:2:"57";} </code></pre> <p>Here's how i stored 'the_users' user meta data:</p> <pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) &amp;&amp; is_array($the_following_users)){ $the_following_users[] = $user_follow_to; } else { $the_following_users = array($user_follow_to); } update_user_meta($the_follower, "the_following_users", $the_following_users); </code></pre>
[ { "answer_id": 289636, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So s...
2017/12/27
[ "https://wordpress.stackexchange.com/questions/289634", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133343/" ]
This is my code: ``` $args = array ( 'order' => 'DESC', 'include' => get_user_meta($author->ID, 'the_following_users', true) ); $wp_user_query = new WP_User_Query( $args ); $users = $wp_user_query->get_results(); if ( ! empty( $users ) ) { foreach ( $users as $user ) { // Get users } } else { echo 'Error.'; } ``` The user meta 'the\_users' may be empty so if it's empty it's got to me all registered users if not empty it's print the users that I need. The problem that `if ( ! empty( $users ) ) { }` is not reading if 'include' is empty or not, I know I can make a variable and check first if the variable is empty or not but I don't need this I want to check if 'include' is empty by using '$wp\_user\_query->get\_results()'. **EDIT:** As Nicolai answer we can replace true to false from get\_user\_meta code and the problem will be solved and if the include is empty the WP-User\_Query will return a false and print error. The problem now that if include not empty so the code must be working without any issues but that does not happen it ignores the users that stored in 'the\_users' user meta and print only current user. Here's the value of 'the\_users' user meta: ``` a:19:{i:0;s:2:"89";i:3;s:3:"105";i:4;s:2:"74";i:5;s:3:"111";i:6;s:3:"167";i:7;s:2:"83";i:8;s:2:"54";i:9;s:2:"87";i:10;s:2:"85";i:11;s:2:"77";i:13;s:2:"82";i:14;s:2:"60";i:15;s:3:"149";i:16;s:3:"160";i:17;s:2:"71";i:18;s:1:"3";i:19;s:1:"2";i:20;s:3:"121";i:21;s:2:"57";} ``` Here's how i stored 'the\_users' user meta data: ``` $the_following_users = get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){ $the_following_users[] = $user_follow_to; } else { $the_following_users = array($user_follow_to); } update_user_meta($the_follower, "the_following_users", $the_following_users); ```
I think the problem here is that in the process of violating this rule, you've created confusion and problems: > > do 1 thing per statement, 1 statement per line > > > Coupled with another problem: > > Passing arrays to the APIs which get stored as serialised PHP ( security issue ) > > > And another: > > Always check your assumptions > > > it ignores the users that stored in 'the\_users' user meta and print only current user. > > > That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added. Run through this code in your mind, e.g.: ``` $the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){ $the_following_users[] = $user_follow_to; ``` Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string. So lets fix the saving: ``` $the_following_users = get_user_meta($the_follower, "the_following_users", true); if ( empty( $the_following_users ) ) { $the_following_user = array(); } ``` Then lets simplify the next part: ``` $the_following_users[] = $user_follow_to; ``` And fix the saving so that it's not a security risk: ``` $following = implode( ',', $the_following_users ); update_user_meta($the_follower, "the_following_users", $following ); ``` Finally, lets move to the frontend: Firstly, we assume the `get_user_meta` works, but never check if this is true: ``` $args = array ( 'order' => 'DESC', 'include' => get_user_meta($author->ID, 'the_following_users', true) ); ``` What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format: ``` $include = get_user_meta($author->ID, 'the_following_users', true); if ( empty( $include ) ) { // the user follows nobody, or has not followed anybody yet! } else { // turn the string into an array $include = explode( ',', $include ); $args = array ( 'order' => 'DESC', 'include' => $include ); // etc... } ``` A Final Note ============ Your loop looks like this: ``` foreach ( $users as $user ) { // Get users } ``` But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g. ``` foreach ( $users as $user ) { // Get users echo esc_html( $user->first_name . ' ' . $user->last_name ); } ```
289,640
<p>I'm using Tevolution. I can't find where I can re-size the flag at the top of this website: <a href="http://www.isupportblack.com/" rel="nofollow noreferrer">isupportblack.com</a> It is blurry and shouldn't be. Any suggestions? Thanks!</p>
[ { "answer_id": 289636, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So s...
2017/12/28
[ "https://wordpress.stackexchange.com/questions/289640", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133907/" ]
I'm using Tevolution. I can't find where I can re-size the flag at the top of this website: [isupportblack.com](http://www.isupportblack.com/) It is blurry and shouldn't be. Any suggestions? Thanks!
I think the problem here is that in the process of violating this rule, you've created confusion and problems: > > do 1 thing per statement, 1 statement per line > > > Coupled with another problem: > > Passing arrays to the APIs which get stored as serialised PHP ( security issue ) > > > And another: > > Always check your assumptions > > > it ignores the users that stored in 'the\_users' user meta and print only current user. > > > That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added. Run through this code in your mind, e.g.: ``` $the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){ $the_following_users[] = $user_follow_to; ``` Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string. So lets fix the saving: ``` $the_following_users = get_user_meta($the_follower, "the_following_users", true); if ( empty( $the_following_users ) ) { $the_following_user = array(); } ``` Then lets simplify the next part: ``` $the_following_users[] = $user_follow_to; ``` And fix the saving so that it's not a security risk: ``` $following = implode( ',', $the_following_users ); update_user_meta($the_follower, "the_following_users", $following ); ``` Finally, lets move to the frontend: Firstly, we assume the `get_user_meta` works, but never check if this is true: ``` $args = array ( 'order' => 'DESC', 'include' => get_user_meta($author->ID, 'the_following_users', true) ); ``` What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format: ``` $include = get_user_meta($author->ID, 'the_following_users', true); if ( empty( $include ) ) { // the user follows nobody, or has not followed anybody yet! } else { // turn the string into an array $include = explode( ',', $include ); $args = array ( 'order' => 'DESC', 'include' => $include ); // etc... } ``` A Final Note ============ Your loop looks like this: ``` foreach ( $users as $user ) { // Get users } ``` But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g. ``` foreach ( $users as $user ) { // Get users echo esc_html( $user->first_name . ' ' . $user->last_name ); } ```
289,666
<p>When I try to upload any PNG file, I get the following error message:</p> <p><a href="https://i.stack.imgur.com/JYE8w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JYE8w.png" alt="enter image description here"></a></p> <p>I have no plugin or anything installed, that could cause this. I even added the following line in order to fix this:</p> <p><code>define('ALLOW_UNFILTERED_UPLOADS', true);</code></p> <p>Since it is a local installation, security is not an issue. But still this didn't fix my problem. Any ideas what could cause this problem?</p>
[ { "answer_id": 289636, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So s...
2017/12/28
[ "https://wordpress.stackexchange.com/questions/289666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118091/" ]
When I try to upload any PNG file, I get the following error message: [![enter image description here](https://i.stack.imgur.com/JYE8w.png)](https://i.stack.imgur.com/JYE8w.png) I have no plugin or anything installed, that could cause this. I even added the following line in order to fix this: `define('ALLOW_UNFILTERED_UPLOADS', true);` Since it is a local installation, security is not an issue. But still this didn't fix my problem. Any ideas what could cause this problem?
I think the problem here is that in the process of violating this rule, you've created confusion and problems: > > do 1 thing per statement, 1 statement per line > > > Coupled with another problem: > > Passing arrays to the APIs which get stored as serialised PHP ( security issue ) > > > And another: > > Always check your assumptions > > > it ignores the users that stored in 'the\_users' user meta and print only current user. > > > That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added. Run through this code in your mind, e.g.: ``` $the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){ $the_following_users[] = $user_follow_to; ``` Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string. So lets fix the saving: ``` $the_following_users = get_user_meta($the_follower, "the_following_users", true); if ( empty( $the_following_users ) ) { $the_following_user = array(); } ``` Then lets simplify the next part: ``` $the_following_users[] = $user_follow_to; ``` And fix the saving so that it's not a security risk: ``` $following = implode( ',', $the_following_users ); update_user_meta($the_follower, "the_following_users", $following ); ``` Finally, lets move to the frontend: Firstly, we assume the `get_user_meta` works, but never check if this is true: ``` $args = array ( 'order' => 'DESC', 'include' => get_user_meta($author->ID, 'the_following_users', true) ); ``` What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format: ``` $include = get_user_meta($author->ID, 'the_following_users', true); if ( empty( $include ) ) { // the user follows nobody, or has not followed anybody yet! } else { // turn the string into an array $include = explode( ',', $include ); $args = array ( 'order' => 'DESC', 'include' => $include ); // etc... } ``` A Final Note ============ Your loop looks like this: ``` foreach ( $users as $user ) { // Get users } ``` But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g. ``` foreach ( $users as $user ) { // Get users echo esc_html( $user->first_name . ' ' . $user->last_name ); } ```
289,690
<p>I'm trying to figure out how to query posts on a custom post type, using a custom field. </p> <p>Goal: On my "artists" single page, I want to display a list of news/album releases for that artist only. Those posts will also show up on the main page. </p> <p>Concept:<br> Use a category for each artist on the posts; use a custom field "news_category_slug" on each artist page to link them. I then want to query posts and display all posts in the category that match the custom value "news_category_slug". </p> <p>Maybe I'm going about this the wrong way; I don't have much PHP knowledge so I'm having trouble figuring out if this is a bad approach or if I just don't understand how to nest a variable inside the query! Help!</p>
[ { "answer_id": 289636, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So s...
2017/12/28
[ "https://wordpress.stackexchange.com/questions/289690", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133951/" ]
I'm trying to figure out how to query posts on a custom post type, using a custom field. Goal: On my "artists" single page, I want to display a list of news/album releases for that artist only. Those posts will also show up on the main page. Concept: Use a category for each artist on the posts; use a custom field "news\_category\_slug" on each artist page to link them. I then want to query posts and display all posts in the category that match the custom value "news\_category\_slug". Maybe I'm going about this the wrong way; I don't have much PHP knowledge so I'm having trouble figuring out if this is a bad approach or if I just don't understand how to nest a variable inside the query! Help!
I think the problem here is that in the process of violating this rule, you've created confusion and problems: > > do 1 thing per statement, 1 statement per line > > > Coupled with another problem: > > Passing arrays to the APIs which get stored as serialised PHP ( security issue ) > > > And another: > > Always check your assumptions > > > it ignores the users that stored in 'the\_users' user meta and print only current user. > > > That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added. Run through this code in your mind, e.g.: ``` $the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){ $the_following_users[] = $user_follow_to; ``` Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string. So lets fix the saving: ``` $the_following_users = get_user_meta($the_follower, "the_following_users", true); if ( empty( $the_following_users ) ) { $the_following_user = array(); } ``` Then lets simplify the next part: ``` $the_following_users[] = $user_follow_to; ``` And fix the saving so that it's not a security risk: ``` $following = implode( ',', $the_following_users ); update_user_meta($the_follower, "the_following_users", $following ); ``` Finally, lets move to the frontend: Firstly, we assume the `get_user_meta` works, but never check if this is true: ``` $args = array ( 'order' => 'DESC', 'include' => get_user_meta($author->ID, 'the_following_users', true) ); ``` What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format: ``` $include = get_user_meta($author->ID, 'the_following_users', true); if ( empty( $include ) ) { // the user follows nobody, or has not followed anybody yet! } else { // turn the string into an array $include = explode( ',', $include ); $args = array ( 'order' => 'DESC', 'include' => $include ); // etc... } ``` A Final Note ============ Your loop looks like this: ``` foreach ( $users as $user ) { // Get users } ``` But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g. ``` foreach ( $users as $user ) { // Get users echo esc_html( $user->first_name . ' ' . $user->last_name ); } ```
289,691
<p>I tried to remove /category/ base from permalink structure, keeping parent category, but Wordpress gives me back 404 error page.</p> <p>I'm not using any particular plugin to do that, only using . in category base and using %category%/%postname%/ as permalink structure.</p> <p>If I restore /category/ base everything works fine. I have already used '/' and '.' to remove category base.</p> <p>How can I solve the problem? </p>
[ { "answer_id": 289636, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So s...
2017/12/28
[ "https://wordpress.stackexchange.com/questions/289691", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103072/" ]
I tried to remove /category/ base from permalink structure, keeping parent category, but Wordpress gives me back 404 error page. I'm not using any particular plugin to do that, only using . in category base and using %category%/%postname%/ as permalink structure. If I restore /category/ base everything works fine. I have already used '/' and '.' to remove category base. How can I solve the problem?
I think the problem here is that in the process of violating this rule, you've created confusion and problems: > > do 1 thing per statement, 1 statement per line > > > Coupled with another problem: > > Passing arrays to the APIs which get stored as serialised PHP ( security issue ) > > > And another: > > Always check your assumptions > > > it ignores the users that stored in 'the\_users' user meta and print only current user. > > > That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added. Run through this code in your mind, e.g.: ``` $the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true); if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){ $the_following_users[] = $user_follow_to; ``` Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string. So lets fix the saving: ``` $the_following_users = get_user_meta($the_follower, "the_following_users", true); if ( empty( $the_following_users ) ) { $the_following_user = array(); } ``` Then lets simplify the next part: ``` $the_following_users[] = $user_follow_to; ``` And fix the saving so that it's not a security risk: ``` $following = implode( ',', $the_following_users ); update_user_meta($the_follower, "the_following_users", $following ); ``` Finally, lets move to the frontend: Firstly, we assume the `get_user_meta` works, but never check if this is true: ``` $args = array ( 'order' => 'DESC', 'include' => get_user_meta($author->ID, 'the_following_users', true) ); ``` What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format: ``` $include = get_user_meta($author->ID, 'the_following_users', true); if ( empty( $include ) ) { // the user follows nobody, or has not followed anybody yet! } else { // turn the string into an array $include = explode( ',', $include ); $args = array ( 'order' => 'DESC', 'include' => $include ); // etc... } ``` A Final Note ============ Your loop looks like this: ``` foreach ( $users as $user ) { // Get users } ``` But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g. ``` foreach ( $users as $user ) { // Get users echo esc_html( $user->first_name . ' ' . $user->last_name ); } ```
289,735
<p>Hi i am using the following to modify the results returned from a search on the users tables in wp admin :</p> <pre><code>add_action('pre_get_users','custom_user_search'); $query-&gt;query_vars['meta_query'] = array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'billing_postcode', 'value' =&gt; str_replace('*', '', $query-&gt;query_vars['search']), 'compare' =&gt; 'LIKE' ), </code></pre> <p>);</p> <p>This returns the expected results on a standard table load, but when not in conjunction with a search returns an empty set. Can someone explain why this?</p>
[ { "answer_id": 289743, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 0, "selected": false, "text": "<p>The query built in this way will search for users by their standard properties <code>AND</code> by this m...
2017/12/29
[ "https://wordpress.stackexchange.com/questions/289735", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101873/" ]
Hi i am using the following to modify the results returned from a search on the users tables in wp admin : ``` add_action('pre_get_users','custom_user_search'); $query->query_vars['meta_query'] = array( 'relation' => 'OR', array( 'key' => 'billing_postcode', 'value' => str_replace('*', '', $query->query_vars['search']), 'compare' => 'LIKE' ), ``` ); This returns the expected results on a standard table load, but when not in conjunction with a search returns an empty set. Can someone explain why this?
OK, Here's how I did it : ``` add_action('pre_user_query', 'custom_user_list_queries'); function custom_user_list_queries($query){ if(!empty($query->query_vars['search'])) { $query->query_from .= " LEFT OUTER JOIN wp_usermeta AS alias ON (wp_users.ID = alias.user_id)";//note use of alias $query->query_where .= " OR ". "(alias.meta_key = 'billing_postcode' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ". " OR ". "(alias.meta_key = 'first_name' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ". " OR ". "(alias.meta_key = 'last_name' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ". " OR ". "(alias.meta_key = 'chat_name' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') "; } } ```
289,749
<p>It is possible to change colors of <a href="https://developer.wordpress.org/resource/dashicons/#chart-bar" rel="nofollow noreferrer">DashIcons</a> with CSS? I couldnt get it to work.</p>
[ { "answer_id": 289752, "author": "DekiGk", "author_id": 69750, "author_profile": "https://wordpress.stackexchange.com/users/69750", "pm_score": 4, "selected": true, "text": "<p>Yes, this is possible. Make sure your CSS selector is correct. You can target the specific HTML element or its ...
2017/12/29
[ "https://wordpress.stackexchange.com/questions/289749", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
It is possible to change colors of [DashIcons](https://developer.wordpress.org/resource/dashicons/#chart-bar) with CSS? I couldnt get it to work.
Yes, this is possible. Make sure your CSS selector is correct. You can target the specific HTML element or its `::before` pseudo element and change colour with CSS. Can you post your HTML snippet of the element you want to change and the CSS selector you are using? Maybe you mean to change the colour inside WP admin area for all dash-icons? In that case: ``` .dashicons { color: red; } ```
289,759
<p>Found this and it works, but want to change the 10 MB limit to 5 GB.</p> <pre><code>$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) &gt; ( 1024 * 1024 * 10 ) ); </code></pre> <hr> <pre><code>add_filter( 'wp_handle_upload', 'wpse47580_update_upload_stats' ); function wpse47580_update_upload_stats( $args ) { $size = filesize( $args['file'] ); $user_id = get_current_user_id(); $upload_count = get_user_meta( $user_id, 'upload_count', true ); $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true ); update_user_meta( $user_id, 'upload_count', $upload_count + 1 ); update_user_meta( $user_id, 'upload_bytes', $upload_bytes + $size ); } </code></pre> <h1>This function runs before the file is uploaded.</h1> <pre><code>add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' ); function wpse47580_check_upload_limits( $file ) { $user_id = get_current_user_id(); $upload_count = get_user_meta( $user_id, 'upload_count', true ); $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true ); $filesize = $file['size']; // bytes $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) &gt; ( 1024 * 1024 * 10 ) ); $upload_count_limit_reached = ( $upload_count + 1 ) &gt; 100; if ( $upload_count_limit_reached || $upload_bytes_limit_reached ) $file['error'] = 'Upload limit has been reached for this account!'; return $file; } </code></pre>
[ { "answer_id": 289765, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>You have to set <a href=\"https://wordpress.stackexchange.com/questions/252849/wordpress-media-uplo...
2017/12/29
[ "https://wordpress.stackexchange.com/questions/289759", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133947/" ]
Found this and it works, but want to change the 10 MB limit to 5 GB. ``` $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( 1024 * 1024 * 10 ) ); ``` --- ``` add_filter( 'wp_handle_upload', 'wpse47580_update_upload_stats' ); function wpse47580_update_upload_stats( $args ) { $size = filesize( $args['file'] ); $user_id = get_current_user_id(); $upload_count = get_user_meta( $user_id, 'upload_count', true ); $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true ); update_user_meta( $user_id, 'upload_count', $upload_count + 1 ); update_user_meta( $user_id, 'upload_bytes', $upload_bytes + $size ); } ``` This function runs before the file is uploaded. =============================================== ``` add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' ); function wpse47580_check_upload_limits( $file ) { $user_id = get_current_user_id(); $upload_count = get_user_meta( $user_id, 'upload_count', true ); $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true ); $filesize = $file['size']; // bytes $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( 1024 * 1024 * 10 ) ); $upload_count_limit_reached = ( $upload_count + 1 ) > 100; if ( $upload_count_limit_reached || $upload_bytes_limit_reached ) $file['error'] = 'Upload limit has been reached for this account!'; return $file; } ```
I have it working. I removed the top half of the script. Don't know why it now works, but tested it and does what I wanted. Thanks for all your help and support. The original thread can be found [here](https://wordpress.stackexchange.com/q/47580/22534), for those interested. ``` add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' ); function wpse47580_check_upload_limits( $file ) { $user_id = get_current_user_id(); $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true ); $filesize = $file['size']; // bytes $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( GB_IN_BYTES * 5 ) ); if ( $upload_bytes_limit_reached ) $file['error'] = 'Upload limit has been reached for this account!'; return $file; } ```
289,763
<p>I am using the Enhanced Image Library plugin to automatically add a taxonomy to images uploaded to a custom post type. The plugin has a feature that will allow the post's categories to be automatically added to associated images when the image is uploaded.</p> <p>However, if the post category is not assigned to the post before the images are added, then the images will not be categorized correctly. The easiest solution would be if there was a way to assign a default category directly after the "New Post" button was clicked, before the user has a chance to input any data into the post fields, and well before the save_post action.</p> <p>All of the answers to this question that I found seem to reference the save_post or publish_post actions. Is there any action that can be utilized when "new post" is initially clicked?</p> <p>If there is not, do you have any other suggestions? Should I attempt to add javascript somewhere to pre-check this field in a post admin template? If so, where should I find that?</p>
[ { "answer_id": 289765, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>You have to set <a href=\"https://wordpress.stackexchange.com/questions/252849/wordpress-media-uplo...
2017/12/29
[ "https://wordpress.stackexchange.com/questions/289763", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134003/" ]
I am using the Enhanced Image Library plugin to automatically add a taxonomy to images uploaded to a custom post type. The plugin has a feature that will allow the post's categories to be automatically added to associated images when the image is uploaded. However, if the post category is not assigned to the post before the images are added, then the images will not be categorized correctly. The easiest solution would be if there was a way to assign a default category directly after the "New Post" button was clicked, before the user has a chance to input any data into the post fields, and well before the save\_post action. All of the answers to this question that I found seem to reference the save\_post or publish\_post actions. Is there any action that can be utilized when "new post" is initially clicked? If there is not, do you have any other suggestions? Should I attempt to add javascript somewhere to pre-check this field in a post admin template? If so, where should I find that?
I have it working. I removed the top half of the script. Don't know why it now works, but tested it and does what I wanted. Thanks for all your help and support. The original thread can be found [here](https://wordpress.stackexchange.com/q/47580/22534), for those interested. ``` add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' ); function wpse47580_check_upload_limits( $file ) { $user_id = get_current_user_id(); $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true ); $filesize = $file['size']; // bytes $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( GB_IN_BYTES * 5 ) ); if ( $upload_bytes_limit_reached ) $file['error'] = 'Upload limit has been reached for this account!'; return $file; } ```
289,769
<p>In the WooCommerce plugin, the PayPal gateway has recently been updated to capture payment on status change TO either "Processing" or "Completed".</p> <p>We want to ONLY allow capture after order status has been updated to COMPLETED.</p> <p>In order to do this, I have identified that I need to remove an action. The action is location in class-wc-gateway-paypal.php and the code is below:</p> <pre><code>class WC_Gateway_Paypal extends WC_Payment_Gateway { /** @var bool Whether or not logging is enabled */ public static $log_enabled = false; /** @var WC_Logger Logger instance */ public static $log = false; /** * Constructor for the gateway. */ public function __construct() { $this-&gt;id = 'paypal'; $this-&gt;has_fields = false; $this-&gt;order_button_text = __( 'Proceed to PayPal', 'woocommerce' ); $this-&gt;method_title = __( 'PayPal', 'woocommerce' ); $this-&gt;method_description = sprintf( __( 'PayPal Standard sends customers to PayPal to enter their payment information. PayPal IPN requires fsockopen/cURL support to update order statuses after payment. Check the &lt;a href="%s"&gt;system status&lt;/a&gt; page for more details.', 'woocommerce' ), admin_url( 'admin.php?page=wc-status' ) ); $this-&gt;supports = array( 'products', 'refunds', ); // Load the settings. $this-&gt;init_form_fields(); $this-&gt;init_settings(); // Define user set variables. $this-&gt;title = $this-&gt;get_option( 'title' ); $this-&gt;description = $this-&gt;get_option( 'description' ); $this-&gt;testmode = 'yes' === $this-&gt;get_option( 'testmode', 'no' ); $this-&gt;debug = 'yes' === $this-&gt;get_option( 'debug', 'no' ); $this-&gt;email = $this-&gt;get_option( 'email' ); $this-&gt;receiver_email = $this-&gt;get_option( 'receiver_email', $this-&gt;email ); $this-&gt;identity_token = $this-&gt;get_option( 'identity_token' ); self::$log_enabled = $this-&gt;debug; add_action( 'woocommerce_update_options_payment_gateways_' . $this-&gt;id, array( $this, 'process_admin_options' ) ); add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) ); </code></pre> <p>The final line is the action I want to remove. </p> <pre><code>add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) ); </code></pre> <p>I have my own plugin that I use to call various functions with. Before I screw something up, I am hoping someone can validate (or correct) the code I plan to use:</p> <pre><code>add_action( 'woocommerce_order_status_on-hold_to_completed','remove_PaypalCapture_action' ); function remove_PaypalCapture_action(){ global $WC_Gateway_Paypal; //get access to the class object instance remove_action('woocommerce_order_status_on-hold_to_processing', array($WC_Gateway_Paypal, 'capture_payment' )); //DO NOT capture payment upon order change to processing } </code></pre> <p>Will this work, or am I missing something?</p>
[ { "answer_id": 289780, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>If <em>WooCommerce</em> plugin declares <code>$WC_Gateway_Paypal</code> as global variable:</p...
2017/12/30
[ "https://wordpress.stackexchange.com/questions/289769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134005/" ]
In the WooCommerce plugin, the PayPal gateway has recently been updated to capture payment on status change TO either "Processing" or "Completed". We want to ONLY allow capture after order status has been updated to COMPLETED. In order to do this, I have identified that I need to remove an action. The action is location in class-wc-gateway-paypal.php and the code is below: ``` class WC_Gateway_Paypal extends WC_Payment_Gateway { /** @var bool Whether or not logging is enabled */ public static $log_enabled = false; /** @var WC_Logger Logger instance */ public static $log = false; /** * Constructor for the gateway. */ public function __construct() { $this->id = 'paypal'; $this->has_fields = false; $this->order_button_text = __( 'Proceed to PayPal', 'woocommerce' ); $this->method_title = __( 'PayPal', 'woocommerce' ); $this->method_description = sprintf( __( 'PayPal Standard sends customers to PayPal to enter their payment information. PayPal IPN requires fsockopen/cURL support to update order statuses after payment. Check the <a href="%s">system status</a> page for more details.', 'woocommerce' ), admin_url( 'admin.php?page=wc-status' ) ); $this->supports = array( 'products', 'refunds', ); // Load the settings. $this->init_form_fields(); $this->init_settings(); // Define user set variables. $this->title = $this->get_option( 'title' ); $this->description = $this->get_option( 'description' ); $this->testmode = 'yes' === $this->get_option( 'testmode', 'no' ); $this->debug = 'yes' === $this->get_option( 'debug', 'no' ); $this->email = $this->get_option( 'email' ); $this->receiver_email = $this->get_option( 'receiver_email', $this->email ); $this->identity_token = $this->get_option( 'identity_token' ); self::$log_enabled = $this->debug; add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) ); ``` The final line is the action I want to remove. ``` add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) ); ``` I have my own plugin that I use to call various functions with. Before I screw something up, I am hoping someone can validate (or correct) the code I plan to use: ``` add_action( 'woocommerce_order_status_on-hold_to_completed','remove_PaypalCapture_action' ); function remove_PaypalCapture_action(){ global $WC_Gateway_Paypal; //get access to the class object instance remove_action('woocommerce_order_status_on-hold_to_processing', array($WC_Gateway_Paypal, 'capture_payment' )); //DO NOT capture payment upon order change to processing } ``` Will this work, or am I missing something?
There are two things that you'll need in order to remove the action. 1. The exact instance of WC\_Gateway\_Paypal 2. Knowing when the action is added and when it is executed Without these, it will be difficult, but impossible to remove the action. Getting the instance of WC\_Gateway\_Paypal should be straightforward. ``` //* Make sure class-wc-payment-gateways.php is included once include_once PATH_TO . class-wc-payment-gateways.php; //* Get the gateways $gateways = \WC_Payment_Gateways::instance(); //* The class instances are located in the payment_gateways property $gateways->payment_gateways ``` The Paypal gateway instance should be in this array. I don't have WooCommerce installed on this machine right now, so I don't know exactly how it's stored. But you should be able to figure it out. [Added: Thanks to @willington-vega for finding out how WC stores the payment gateways in the array. I've updated the `get_wc_paypal_payment_gateway()` function below with this.] Fortunately, the action is added at priority 10 to the `woocommerce_order_status_on-hold_to_completed` hook. What we can do is hook in at an earlier priority and remove the hook. ``` add_action( 'woocommerce_order_status_on-hold_to_completed', 'remove_PaypalCapture_action', 9 ); function remove_PaypalCapture_action() { //* This is where we'll remove the action //* Get the instance $WC_Paypal_Payment_Gateway = get_wc_paypal_payment_gateway(); remove_action( 'woocommerce_order_status_on-hold_to_completed', [ $WC_Paypal_Payment_Gateway , 'capture_payment' ] ); } function get_wc_paypal_payment_gateway() { //* Make sure class-wc-payment-gateways.php is included once include_once PATH_TO . class-wc-payment-gateways.php; //* Return the paypal gateway return \WC_Payment_Gateways::instance()->payment_gateways[ 'paypal' ]; } ```
289,794
<p>I'm trying to redirect the user to a "Thank you for signing up" page but I can not get it.</p> <p>This is the code (It's wrong)</p> <pre><code>function tml_action_url( $url, $action, $instance ) { if ( 'login' == $action ) $url = 'url/thanks'; return $url; } add_filter( 'tml_action_url', 'tml_action_url', 10, 3 ); ?&gt; </code></pre> <p>But it does not work as I want.</p> <p>Once the user registers, he takes me to the url:</p> <p>url/?checkemail=registered</p> <p>I do not know how to reference it.</p> <p>Any ideas?</p> <p>Greetings, thank you.</p>
[ { "answer_id": 289780, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>If <em>WooCommerce</em> plugin declares <code>$WC_Gateway_Paypal</code> as global variable:</p...
2017/12/30
[ "https://wordpress.stackexchange.com/questions/289794", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134019/" ]
I'm trying to redirect the user to a "Thank you for signing up" page but I can not get it. This is the code (It's wrong) ``` function tml_action_url( $url, $action, $instance ) { if ( 'login' == $action ) $url = 'url/thanks'; return $url; } add_filter( 'tml_action_url', 'tml_action_url', 10, 3 ); ?> ``` But it does not work as I want. Once the user registers, he takes me to the url: url/?checkemail=registered I do not know how to reference it. Any ideas? Greetings, thank you.
There are two things that you'll need in order to remove the action. 1. The exact instance of WC\_Gateway\_Paypal 2. Knowing when the action is added and when it is executed Without these, it will be difficult, but impossible to remove the action. Getting the instance of WC\_Gateway\_Paypal should be straightforward. ``` //* Make sure class-wc-payment-gateways.php is included once include_once PATH_TO . class-wc-payment-gateways.php; //* Get the gateways $gateways = \WC_Payment_Gateways::instance(); //* The class instances are located in the payment_gateways property $gateways->payment_gateways ``` The Paypal gateway instance should be in this array. I don't have WooCommerce installed on this machine right now, so I don't know exactly how it's stored. But you should be able to figure it out. [Added: Thanks to @willington-vega for finding out how WC stores the payment gateways in the array. I've updated the `get_wc_paypal_payment_gateway()` function below with this.] Fortunately, the action is added at priority 10 to the `woocommerce_order_status_on-hold_to_completed` hook. What we can do is hook in at an earlier priority and remove the hook. ``` add_action( 'woocommerce_order_status_on-hold_to_completed', 'remove_PaypalCapture_action', 9 ); function remove_PaypalCapture_action() { //* This is where we'll remove the action //* Get the instance $WC_Paypal_Payment_Gateway = get_wc_paypal_payment_gateway(); remove_action( 'woocommerce_order_status_on-hold_to_completed', [ $WC_Paypal_Payment_Gateway , 'capture_payment' ] ); } function get_wc_paypal_payment_gateway() { //* Make sure class-wc-payment-gateways.php is included once include_once PATH_TO . class-wc-payment-gateways.php; //* Return the paypal gateway return \WC_Payment_Gateways::instance()->payment_gateways[ 'paypal' ]; } ```
289,812
<p>I've never thought to do this with WordPress until now, but I was wondering is it possible for two templates to be chosen to create a post or page in WordPress?</p> <p>When you are on the 'Edit Page' there is the 'Page Attributes>Template' section. When a custom template is chosen that will generate the main layout of the page which includes the region for an <code>iframe</code>. The <code>iframe</code> comes into play when the <code>custom-field</code> below the content editor is filled out, which would automatically call the second custom template when the page is published.</p> <p>So basically, for the sake of a visual, imagine a comparison site with side-by-side view of two pages. Only now think of that example as a side-by-side view of data inputted into <code>the_content</code> (WP content editor) and <code>custom_field</code> (custom field box/field below the WP content editor).</p> <p>The <code>iframe</code> is needed, but if you know what other code could be used to produce the same results would be fine.</p>
[ { "answer_id": 289833, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 1, "selected": false, "text": "<p>No, you would not use two page-templates on a single page.</p>\n\n<p>Yes, you can have a different admin-p...
2017/12/30
[ "https://wordpress.stackexchange.com/questions/289812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58726/" ]
I've never thought to do this with WordPress until now, but I was wondering is it possible for two templates to be chosen to create a post or page in WordPress? When you are on the 'Edit Page' there is the 'Page Attributes>Template' section. When a custom template is chosen that will generate the main layout of the page which includes the region for an `iframe`. The `iframe` comes into play when the `custom-field` below the content editor is filled out, which would automatically call the second custom template when the page is published. So basically, for the sake of a visual, imagine a comparison site with side-by-side view of two pages. Only now think of that example as a side-by-side view of data inputted into `the_content` (WP content editor) and `custom_field` (custom field box/field below the WP content editor). The `iframe` is needed, but if you know what other code could be used to produce the same results would be fine.
No, you would not use two page-templates on a single page. Yes, you can have a different admin-page layout / configuration for different page-templates. Page-template-A could have two post-editors and page-template-B (or post-format for that matter) could have only a name, email, and featured-image. You could use a single page template and separate includes to help organize your code. ``` <?php // Template Name: 289812 ?> <div class="page-tpl-289812"> <?php get_template_part( 'filename_foo' ); ?> <?php get_template_part( 'filename_bar' ); ?> </div> ``` Add `filename_foo` and `filename_bar` to your theme. `filename_foo` outputs one editor-section and `filename_bar` outputs the other. There are many ways to add additional custom input to the admin-side of anything in WordPress which I won't discuss here.
289,820
<p>****SEE Edits below****</p> <p><strong>Edit added 1/4/2018</strong> I started over again, following the instructions. As far as I can tell everything is correct including the synchronization plugin. fpw-sync-users.php in test.oursite.com 3 occurences of $other_prefixes = array( 'wp5l_', ); fpw-sync-users.php in forum.oursite.com 3 occurrences of $other_prefixes = array( 'wp7g_', ); Is that correct? What happens when I try to log in on either site is it just refreshes the login page and nothing happens. There are no error messages </p> <p>****END EDIT****</p> <p>My organization is using WordPress 4.9.1.</p> <p>What we are hoping to accomplish is having members create a user profile on secure.oursite.org and when they login, they will have access to forums.oursite.org. </p> <p>I have not been able to find updated instructions to complete this task. Can anyone here tell me what I need to do to accomplish this, or where to get the updated instructions?</p> <p>Thank you</p> <p>****ADDITIONAL Information***** I followed the instructions from @Frank P. at that link multiple times, and it is not working. I had to put everything back the way it originally was. Please see below for the steps I took and let me know if I did anything wrong. </p> <p>The sites that I tried to test a Single Logon setup on are on subdomains: test.oursite.com and forum.oursite.com </p> <p>test.oursite.com's database prefix is wp7g forum.oursite.com's datebase prefix is wp5l</p> <p>I want test.oursite.com to be where the user is created. </p> <ol> <li><p>I exported all the database tables from forum.oursite.com (except for wp5l_user and wp5l_usermeta) and imported them into the test.oursite.com datebase. </p></li> <li><p>I went in to edit the wp-config.php files as instructed by Frank P. at this link <a href="https://wordpress.stackexchange.com/questions/272122/single-sign-on-between-two-wordpress-website">Single sign on between two wordpress website</a> He says both wp-config.php files must be identical, except for the prefixes at $table_prefix, which should show the original prefix of their database. Since I want the login to be created in test.oursite.com, I copied the entire wp-config.php file to forum.oursite.com's root.</p></li> <li><p>I went in to edit forum.oursite.com's wp-config.php file and changed the $table_prefix to wp5l then saved it. </p></li> <li><p>I went to edit wp-config.php for test.oursite.com and added the below defines and saved it.</p> <p>define('COOKIE_DOMAIN', '.test.oursite.com'); //this is where I think the problem might be define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM_USER_TABLE', 'wp7g_users'); define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta');</p></li> <li><p>I copied and pasted those same defines to wp-config.php in forum.oursite.com and saved it.</p></li> <li><p>I created the mu-plugins folder in wp-content for both test.oursite.com and forum.oursite.org</p></li> </ol> <p>7 I created fpw-sync-users.php in the mu-plugins folder for test.oursite.com and copied Frank P's code, then changed the 3 areas to my prefix and saved it as you see below.</p> <pre><code>$other_prefixes = array( 'wp7g_', ); </code></pre> <ol start="8"> <li>I created fpw-sync-users.php in the mu-plugins folder for forums.oursite.com and copied the same code from the test.oursite.com mu-plugins folder so that the prefix is wp7g as Frank said it should be. I saved it. </li> </ol> <p>That was apparently the last step. I went to test.oursite.com and logged in, then went to forum.oursite.com and saw that I was not logged in there. I went to wp-login.php and tried to login with the same credentials from test.oursite.com. It did not accept those credentials. I tried to log in with the original admin credentials and it would not accept those either. So I tried again to make these custom configurations work several more times, trying different things in case I misunderstood something. Nothing is working. I am hoping someone can look over the steps I have taken and tell me what I am missing. </p> <p>Thank you.</p> <p>******wp-config.php for test.oursite.com*****</p> <pre><code>&lt;?php /** * The base configuration for WordPress * * The wp-config.php creation script uses this file during the * installation. You don't have to use the web site, you can * copy this file to "wp-config.php" and fill in the values. * * This file contains the following configurations: * * * MySQL settings * * Secret keys * * Database table prefix * * ABSPATH * * @link https://codex.wordpress.org/Editing_wp-config.php * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'oursite_test2'); /** MySQL database username */ define('DB_USER', 'oursite_test2'); /** MySQL database password */ define('DB_PASSWORD', 'hidden'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'hidden'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY',hidden'); define('SECURE_AUTH_KEY', 'hidden'); define('LOGGED_IN_KEY', 'hidden'); define('NONCE_KEY', 'hidden'); define('AUTH_SALT', 'hidden'); define('SECURE_AUTH_SALT', 'hidden'); define('LOGGED_IN_SALT', 'hidden'); define('NONCE_SALT', 'hidden'); define('COOKIE_DOMAIN', '.test.oursite.com'); define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM_USER_TABLE', 'wp7g_users'); define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each * a unique prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp7g_'; /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. * * For information on other constants that can be used for debugging, * visit the Codex. * * @link https://codex.wordpress.org/Debugging_in_WordPress */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); ****wp-config.php for forum.oursite.com***** &lt;?php /** * The base configuration for WordPress * * The wp-config.php creation script uses this file during the * installation. You don't have to use the web site, you can * copy this file to "wp-config.php" and fill in the values. * * This file contains the following configurations: * * * MySQL settings * * Secret keys * * Database table prefix * * ABSPATH * * @link https://codex.wordpress.org/Editing_wp-config.php * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'oursite_test2'); /** MySQL database username */ define('DB_USER', 'oursite_test2'); /** MySQL database password */ define('DB_PASSWORD', 'hidden'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'hidden'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY',hidden'); define('SECURE_AUTH_KEY', 'hidden'); define('LOGGED_IN_KEY', 'hidden'); define('NONCE_KEY', 'hidden'); define('AUTH_SALT', 'hidden'); define('SECURE_AUTH_SALT', 'hidden'); define('LOGGED_IN_SALT', 'hidden'); define('NONCE_SALT', 'hidden'); define('COOKIE_DOMAIN', '.test.oursite.com'); define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM_USER_TABLE', 'wp7g_users'); define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each * a unique prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp5l_'; /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. * * For information on other constants that can be used for debugging, * visit the Codex. * * @link https://codex.wordpress.org/Debugging_in_WordPress */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); </code></pre>
[ { "answer_id": 289850, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>In both <code>wp-config.php</code> files, change the following defines:</p>\n\n<pre><code>defi...
2017/12/31
[ "https://wordpress.stackexchange.com/questions/289820", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134043/" ]
\*\*\*\*SEE Edits below\*\*\*\* **Edit added 1/4/2018** I started over again, following the instructions. As far as I can tell everything is correct including the synchronization plugin. fpw-sync-users.php in test.oursite.com 3 occurences of $other\_prefixes = array( 'wp5l\_', ); fpw-sync-users.php in forum.oursite.com 3 occurrences of $other\_prefixes = array( 'wp7g\_', ); Is that correct? What happens when I try to log in on either site is it just refreshes the login page and nothing happens. There are no error messages \*\*\*\*END EDIT\*\*\*\* My organization is using WordPress 4.9.1. What we are hoping to accomplish is having members create a user profile on secure.oursite.org and when they login, they will have access to forums.oursite.org. I have not been able to find updated instructions to complete this task. Can anyone here tell me what I need to do to accomplish this, or where to get the updated instructions? Thank you \*\*\*\*ADDITIONAL Information\*\*\*\*\* I followed the instructions from @Frank P. at that link multiple times, and it is not working. I had to put everything back the way it originally was. Please see below for the steps I took and let me know if I did anything wrong. The sites that I tried to test a Single Logon setup on are on subdomains: test.oursite.com and forum.oursite.com test.oursite.com's database prefix is wp7g forum.oursite.com's datebase prefix is wp5l I want test.oursite.com to be where the user is created. 1. I exported all the database tables from forum.oursite.com (except for wp5l\_user and wp5l\_usermeta) and imported them into the test.oursite.com datebase. 2. I went in to edit the wp-config.php files as instructed by Frank P. at this link [Single sign on between two wordpress website](https://wordpress.stackexchange.com/questions/272122/single-sign-on-between-two-wordpress-website) He says both wp-config.php files must be identical, except for the prefixes at $table\_prefix, which should show the original prefix of their database. Since I want the login to be created in test.oursite.com, I copied the entire wp-config.php file to forum.oursite.com's root. 3. I went in to edit forum.oursite.com's wp-config.php file and changed the $table\_prefix to wp5l then saved it. 4. I went to edit wp-config.php for test.oursite.com and added the below defines and saved it. define('COOKIE\_DOMAIN', '.test.oursite.com'); //this is where I think the problem might be define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM\_USER\_TABLE', 'wp7g\_users'); define('CUSTOM\_USER\_META\_TABLE', 'wp7g\_usermeta'); 5. I copied and pasted those same defines to wp-config.php in forum.oursite.com and saved it. 6. I created the mu-plugins folder in wp-content for both test.oursite.com and forum.oursite.org 7 I created fpw-sync-users.php in the mu-plugins folder for test.oursite.com and copied Frank P's code, then changed the 3 areas to my prefix and saved it as you see below. ``` $other_prefixes = array( 'wp7g_', ); ``` 8. I created fpw-sync-users.php in the mu-plugins folder for forums.oursite.com and copied the same code from the test.oursite.com mu-plugins folder so that the prefix is wp7g as Frank said it should be. I saved it. That was apparently the last step. I went to test.oursite.com and logged in, then went to forum.oursite.com and saw that I was not logged in there. I went to wp-login.php and tried to login with the same credentials from test.oursite.com. It did not accept those credentials. I tried to log in with the original admin credentials and it would not accept those either. So I tried again to make these custom configurations work several more times, trying different things in case I misunderstood something. Nothing is working. I am hoping someone can look over the steps I have taken and tell me what I am missing. Thank you. \*\*\*\*\*\*wp-config.php for test.oursite.com\*\*\*\*\* ``` <?php /** * The base configuration for WordPress * * The wp-config.php creation script uses this file during the * installation. You don't have to use the web site, you can * copy this file to "wp-config.php" and fill in the values. * * This file contains the following configurations: * * * MySQL settings * * Secret keys * * Database table prefix * * ABSPATH * * @link https://codex.wordpress.org/Editing_wp-config.php * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'oursite_test2'); /** MySQL database username */ define('DB_USER', 'oursite_test2'); /** MySQL database password */ define('DB_PASSWORD', 'hidden'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'hidden'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY',hidden'); define('SECURE_AUTH_KEY', 'hidden'); define('LOGGED_IN_KEY', 'hidden'); define('NONCE_KEY', 'hidden'); define('AUTH_SALT', 'hidden'); define('SECURE_AUTH_SALT', 'hidden'); define('LOGGED_IN_SALT', 'hidden'); define('NONCE_SALT', 'hidden'); define('COOKIE_DOMAIN', '.test.oursite.com'); define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM_USER_TABLE', 'wp7g_users'); define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each * a unique prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp7g_'; /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. * * For information on other constants that can be used for debugging, * visit the Codex. * * @link https://codex.wordpress.org/Debugging_in_WordPress */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); ****wp-config.php for forum.oursite.com***** <?php /** * The base configuration for WordPress * * The wp-config.php creation script uses this file during the * installation. You don't have to use the web site, you can * copy this file to "wp-config.php" and fill in the values. * * This file contains the following configurations: * * * MySQL settings * * Secret keys * * Database table prefix * * ABSPATH * * @link https://codex.wordpress.org/Editing_wp-config.php * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'oursite_test2'); /** MySQL database username */ define('DB_USER', 'oursite_test2'); /** MySQL database password */ define('DB_PASSWORD', 'hidden'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'hidden'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY',hidden'); define('SECURE_AUTH_KEY', 'hidden'); define('LOGGED_IN_KEY', 'hidden'); define('NONCE_KEY', 'hidden'); define('AUTH_SALT', 'hidden'); define('SECURE_AUTH_SALT', 'hidden'); define('LOGGED_IN_SALT', 'hidden'); define('NONCE_SALT', 'hidden'); define('COOKIE_DOMAIN', '.test.oursite.com'); define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM_USER_TABLE', 'wp7g_users'); define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each * a unique prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp5l_'; /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. * * For information on other constants that can be used for debugging, * visit the Codex. * * @link https://codex.wordpress.org/Debugging_in_WordPress */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); ```
In both `wp-config.php` files, change the following defines: ``` define('COOKIE_DOMAIN', '.test.oursite.com'); define('COOKIEHASH', md5('test.oursite.com')); ``` to: ``` define('COOKIE_DOMAIN', '.oursite.com'); define('COOKIEHASH', md5('oursite.com')); ``` Go to `test.oursite.com/wp-admin/` and login as an administrator. Go to `Users -> Your Profile` and click on `Update Profile` button. Now go to `forums.oursite.com/wp-admin/`. You should be logged in there. If synchronization plugins in `mu-plugins` for both sites are correct, all is done. If they are incorrect, you'll get a message, that you don't have privileges to access this page. In that case, you'll have to correct synchronization plugins, according to my original answer. If you see login form, your `wp-config.php` files are not set correctly.
289,836
<p>i have created a meta box oembed with clone:</p> <pre><code>function media( $meta_boxes ) { $prefix = ''; $meta_boxes[] = array( 'id' =&gt; 'media_1', 'title' =&gt; esc_html__( 'Media', 'media' ), 'post_types' =&gt; array( 'post','personal_projects' ), 'context' =&gt; 'advanced', 'priority' =&gt; 'high', 'autosave' =&gt; true, 'fields' =&gt; array( array( 'id' =&gt; $prefix . 'image_advanced_2', 'type' =&gt; 'image_advanced', 'name' =&gt; esc_html__( 'Gallery', 'media' ), ), array( 'id' =&gt; $prefix . 'video_1', 'type' =&gt; 'video', 'name' =&gt; esc_html__( 'Video', 'media' ), ), array( 'id' =&gt; $prefix . 'oembed_1', 'type'=&gt; 'oembed', 'name' =&gt; esc_html__( 'Embed Video', 'media' ), 'clone' =&gt; true, 'add_button' =&gt; esc_html__( 'Add video', 'media' ), 'sort_clone' =&gt; true, ), array( 'id' =&gt; $prefix . 'url_1', 'type' =&gt; 'url', 'name' =&gt; esc_html__( 'URL', 'media' ), 'clone' =&gt; true, ), ), ); return $meta_boxes; } add_filter( 'rwmb_meta_boxes', 'media' ); </code></pre> <p>it works very good except i can not get the videos with foreach</p> <p>i have a vimeo and a youtube video.</p> <pre><code>$btsvideoembeds = array(); $btsvideoembeds = rwmb_meta ( 'oembed_1', array( 'type' =&gt; 'oembed' ) ); foreach ( $btsvideoembeds as $btsvideoembed ) { echo '&lt;div&gt;'; echo $btsvideoembed; echo '&lt;/div&gt;'; } </code></pre> <p>it return string not array</p>
[ { "answer_id": 289837, "author": "Phaidonas Gialis", "author_id": 119240, "author_profile": "https://wordpress.stackexchange.com/users/119240", "pm_score": 1, "selected": false, "text": "<p>i changed the code like this, and now works:</p>\n\n<pre><code>$btsvideoembeds = array();\n$btsvid...
2017/12/31
[ "https://wordpress.stackexchange.com/questions/289836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119240/" ]
i have created a meta box oembed with clone: ``` function media( $meta_boxes ) { $prefix = ''; $meta_boxes[] = array( 'id' => 'media_1', 'title' => esc_html__( 'Media', 'media' ), 'post_types' => array( 'post','personal_projects' ), 'context' => 'advanced', 'priority' => 'high', 'autosave' => true, 'fields' => array( array( 'id' => $prefix . 'image_advanced_2', 'type' => 'image_advanced', 'name' => esc_html__( 'Gallery', 'media' ), ), array( 'id' => $prefix . 'video_1', 'type' => 'video', 'name' => esc_html__( 'Video', 'media' ), ), array( 'id' => $prefix . 'oembed_1', 'type'=> 'oembed', 'name' => esc_html__( 'Embed Video', 'media' ), 'clone' => true, 'add_button' => esc_html__( 'Add video', 'media' ), 'sort_clone' => true, ), array( 'id' => $prefix . 'url_1', 'type' => 'url', 'name' => esc_html__( 'URL', 'media' ), 'clone' => true, ), ), ); return $meta_boxes; } add_filter( 'rwmb_meta_boxes', 'media' ); ``` it works very good except i can not get the videos with foreach i have a vimeo and a youtube video. ``` $btsvideoembeds = array(); $btsvideoembeds = rwmb_meta ( 'oembed_1', array( 'type' => 'oembed' ) ); foreach ( $btsvideoembeds as $btsvideoembed ) { echo '<div>'; echo $btsvideoembed; echo '</div>'; } ``` it return string not array
You could also code it like this : ``` $btsvideoembeds = rwmb_get_value( 'oembed_1', array( 'type' => 'oembed' ) ); foreach ( (array) $btsvideoembeds as $btsvideoembed ) { printf('%s', wp_oembed_get( $btsvideoembed ) ); ```
289,868
<p>that is my source: <a href="http://view-source:buhehe.de" rel="nofollow noreferrer">view-source:buhehe.de</a> i am trying to deque some script form function.php i mean these two:</p> <pre><code>&lt;script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'&gt;&lt;/script&gt; </code></pre> <p>I added following code in Function.php but it doesn't deques scripts from source:</p> <pre><code>function dequeue_script() { wp_dequeue_script( 'http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1' ); wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1' ); wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js' ); } add_action( 'wp_print_scripts', 'dequeue_script', 100 ); </code></pre> <p>How can i deque these scripts fcrom source?</p>
[ { "answer_id": 290029, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>I think is not an problem in your WP installation. The site works as encoding UTF-8, also your feed etc. </p>\n\n...
2018/01/01
[ "https://wordpress.stackexchange.com/questions/289868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133900/" ]
that is my source: [view-source:buhehe.de](http://view-source:buhehe.de) i am trying to deque some script form function.php i mean these two: ``` <script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"></script> <script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script> ``` I added following code in Function.php but it doesn't deques scripts from source: ``` function dequeue_script() { wp_dequeue_script( 'http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1' ); wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1' ); wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js' ); } add_action( 'wp_print_scripts', 'dequeue_script', 100 ); ``` How can i deque these scripts fcrom source?
I've found the issue. UTF8 might produce a multibyte string (when using Hebrew characters for example). Facebook truncates this string a post is shared to keep the description under max number of characters. However, they might truncate a multibyte character in the middle which will result in UTF8 invalid character: � This issue actually reproduces in all multibyte websites. The only workaround I've found is limiting the `og:description` to Facebook's max number of characters (about 110 in comment and 300 in post) I've submitted a bug to Facebook OpenGraph platform and I hope it will be fixed shortly.
289,869
<p>well i can access the sites: </p> <pre><code>www.foo.com and www.bar.com </code></pre> <p>but i cannot access the login - the sites are blank.</p> <pre><code>foo.com/wp-login.php bar.com/wp-login.php </code></pre> <p>i have the following logs.</p> <pre><code>[Mon Jan 01 16:26:03.229924 2018] [core:notice] [pid 17589] AH00052: child pid 24869 exit signal Segmentation fault (11) [Mon Jan 01 16:39:54.242584 2018] [core:notice] [pid 17589] AH00052: child pid 24872 exit signal Segmentation fault (11) [Mon Jan 01 16:39:56.245833 2018] [core:notice] [pid 17589] AH00052: child pid 24870 exit signal Segmentation fault (11) [Mon Jan 01 16:39:56.245959 2018] [core:notice] [pid 17589] AH00052: child pid 24871 exit signal Segmentation fault (11) [Mon Jan 01 16:39:56.246014 2018] [core:notice] [pid 17589] AH00052: child pid 24873 exit signal Segmentation fault (11) [Mon Jan 01 16:49:06.968278 2018] [core:notice] [pid 17589] AH00052: child pid 25032 exit signal Segmentation fault (11) [Mon Jan 01 16:53:03.287697 2018] [core:notice] [pid 17589] AH00052: child pid 25034 exit signal Segmentation fault (11) [Mon Jan 01 16:53:07.293645 2018] [core:notice] [pid 17589] AH00052: child pid 25039 exit signal Segmentation fault (11) [Mon Jan 01 16:53:59.364044 2018] [core:notice] [pid 17589] AH00052: child pid 25106 exit signal Segmentation fault (11) </code></pre> <p>in other words - the admin-area is not acessible</p> <p>what can i do: should i change the wp-login.php url to /login/ to get it to work: so all links in registration and forgot password emails have /login/ rather than wp-login.php.</p>
[ { "answer_id": 289870, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>You probably have a problem-causing plugin. </p>\n\n<p>Look at the error.log file which will tell you ...
2018/01/01
[ "https://wordpress.stackexchange.com/questions/289869", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130711/" ]
well i can access the sites: ``` www.foo.com and www.bar.com ``` but i cannot access the login - the sites are blank. ``` foo.com/wp-login.php bar.com/wp-login.php ``` i have the following logs. ``` [Mon Jan 01 16:26:03.229924 2018] [core:notice] [pid 17589] AH00052: child pid 24869 exit signal Segmentation fault (11) [Mon Jan 01 16:39:54.242584 2018] [core:notice] [pid 17589] AH00052: child pid 24872 exit signal Segmentation fault (11) [Mon Jan 01 16:39:56.245833 2018] [core:notice] [pid 17589] AH00052: child pid 24870 exit signal Segmentation fault (11) [Mon Jan 01 16:39:56.245959 2018] [core:notice] [pid 17589] AH00052: child pid 24871 exit signal Segmentation fault (11) [Mon Jan 01 16:39:56.246014 2018] [core:notice] [pid 17589] AH00052: child pid 24873 exit signal Segmentation fault (11) [Mon Jan 01 16:49:06.968278 2018] [core:notice] [pid 17589] AH00052: child pid 25032 exit signal Segmentation fault (11) [Mon Jan 01 16:53:03.287697 2018] [core:notice] [pid 17589] AH00052: child pid 25034 exit signal Segmentation fault (11) [Mon Jan 01 16:53:07.293645 2018] [core:notice] [pid 17589] AH00052: child pid 25039 exit signal Segmentation fault (11) [Mon Jan 01 16:53:59.364044 2018] [core:notice] [pid 17589] AH00052: child pid 25106 exit signal Segmentation fault (11) ``` in other words - the admin-area is not acessible what can i do: should i change the wp-login.php url to /login/ to get it to work: so all links in registration and forgot password emails have /login/ rather than wp-login.php.
You probably have a problem-causing plugin. Look at the error.log file which will tell you the file that is causing the problem. Rename that plugin's folder (use your hosting control panel's File Manager) and retry. That should get you into the admin area. Then you can contact the plugin's support forum to figure out the fix - or just delete the plugin. Alternately, you can rename the entire plugin folder (in wp-content) so that all plugins are disabled, then move those plugin files individually by their folders to re-enable them. But looking at the error.log file (via your hosting cPanel or via FTP program or hosting File Manager) will help you zero in on the problem.
289,892
<p>I have made wp_query like below. This is some part of them. And it works.</p> <pre><code>$args = .....; $query = new WP_Query($args); while($query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;div class="each"&gt; &lt;h4&gt;&lt;?php the_title(); ?&gt; &lt;/h4&gt; &lt;/div&gt; &lt;?php endwhile; wp_reset_query(); ?&gt; </code></pre> <p>This shows like this.</p> <pre><code>&lt;div&gt;title 1&lt;/div&gt; &lt;div&gt;title 2&lt;/div&gt; &lt;div&gt;title 3&lt;/div&gt; ... </code></pre> <p>At this point, when I click one of the titles, it needs to link to the details of the clicked post. But I don''t know how to link to the detail page. I think it should be linked to 'single.php'. is this right? and how to link to that detail page(maybe singles.php)? thank you.</p>
[ { "answer_id": 289870, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>You probably have a problem-causing plugin. </p>\n\n<p>Look at the error.log file which will tell you ...
2018/01/02
[ "https://wordpress.stackexchange.com/questions/289892", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133185/" ]
I have made wp\_query like below. This is some part of them. And it works. ``` $args = .....; $query = new WP_Query($args); while($query->have_posts() ) : $query->the_post(); ?> <div class="each"> <h4><?php the_title(); ?> </h4> </div> <?php endwhile; wp_reset_query(); ?> ``` This shows like this. ``` <div>title 1</div> <div>title 2</div> <div>title 3</div> ... ``` At this point, when I click one of the titles, it needs to link to the details of the clicked post. But I don''t know how to link to the detail page. I think it should be linked to 'single.php'. is this right? and how to link to that detail page(maybe singles.php)? thank you.
You probably have a problem-causing plugin. Look at the error.log file which will tell you the file that is causing the problem. Rename that plugin's folder (use your hosting control panel's File Manager) and retry. That should get you into the admin area. Then you can contact the plugin's support forum to figure out the fix - or just delete the plugin. Alternately, you can rename the entire plugin folder (in wp-content) so that all plugins are disabled, then move those plugin files individually by their folders to re-enable them. But looking at the error.log file (via your hosting cPanel or via FTP program or hosting File Manager) will help you zero in on the problem.
289,929
<pre><code>if ( ! function_exists( 'loadingscripts' ) ) { function loadingscripts() { // Register the script like this for a theme: wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true ); wp_enqueue_script( 'custom-js' ); /* Load the stylesheets. */ // wp_enqueue_style( 'fontawesome', THEMEROOT . '/inc/lib/fontawesome/css/font-awesome.min.css' ); wp_enqueue_style( 'layout', THEMEROOT . '/css/layout.css' ); wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css' ); } } add_action('wp_enqueue_scripts','loadingscripts'); </code></pre> <p>I think the Javascript is loading before the DOM because in its pure HTML version I was loading the javascript in the footer, but in the WordPress conversion, it doesn't work. What is the fix?</p>
[ { "answer_id": 289932, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>Javascript runs as soon as it's loaded, you need to wait for the DOM ready event, and you do that in JS, not ...
2018/01/02
[ "https://wordpress.stackexchange.com/questions/289929", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` if ( ! function_exists( 'loadingscripts' ) ) { function loadingscripts() { // Register the script like this for a theme: wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true ); wp_enqueue_script( 'custom-js' ); /* Load the stylesheets. */ // wp_enqueue_style( 'fontawesome', THEMEROOT . '/inc/lib/fontawesome/css/font-awesome.min.css' ); wp_enqueue_style( 'layout', THEMEROOT . '/css/layout.css' ); wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css' ); } } add_action('wp_enqueue_scripts','loadingscripts'); ``` I think the Javascript is loading before the DOM because in its pure HTML version I was loading the javascript in the footer, but in the WordPress conversion, it doesn't work. What is the fix?
Javascript runs as soon as it's loaded, you need to wait for the DOM ready event, and you do that in JS, not in WP: ``` jQuery(document).ready(function(){ /* your code here */ }); ```
289,957
<p><img src="https://i.imgur.com/mT1TUjy.png" alt="Taxonomy description"></p> <p>I want to add some helpful text to the edit-tags screen describing the proper use of each of my custom taxonomies. </p> <p>I see <a href="https://codex.wordpress.org/Function_Reference/register_taxonomy" rel="nofollow noreferrer">in the Codex</a> that a description can be added to a custom taxonomy — not to a term, but to the taxonomy itself. That would be a perfect place to put my help text, and I have, but I don't see where that's rendered at all. </p> <p>From the Codex:</p> <blockquote> <p><strong>description</strong> (string) (optional) Include a description of the taxonomy. Default: ""</p> </blockquote> <p>In my custom taxonomy function's $args array:</p> <p><code>$args = array( 'description' =&gt; 'Some helpful text!' [other args...] );</code></p> <p>Is there a hook for edit-tags that I can use to display the taxonomy's description, or another solution (ACF maybe) for inserting help text here? </p>
[ { "answer_id": 289963, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": true, "text": "<p>The code for where you've circled can be found in <code>wp-admin/edit-tags.php:295</code></p>\n\n<p>You'...
2018/01/02
[ "https://wordpress.stackexchange.com/questions/289957", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82256/" ]
![Taxonomy description](https://i.imgur.com/mT1TUjy.png) I want to add some helpful text to the edit-tags screen describing the proper use of each of my custom taxonomies. I see [in the Codex](https://codex.wordpress.org/Function_Reference/register_taxonomy) that a description can be added to a custom taxonomy — not to a term, but to the taxonomy itself. That would be a perfect place to put my help text, and I have, but I don't see where that's rendered at all. From the Codex: > > **description** > (string) (optional) Include a description of the taxonomy. > Default: "" > > > In my custom taxonomy function's $args array: `$args = array( 'description' => 'Some helpful text!' [other args...] );` Is there a hook for edit-tags that I can use to display the taxonomy's description, or another solution (ACF maybe) for inserting help text here?
The code for where you've circled can be found in `wp-admin/edit-tags.php:295` You'll notice there's nothing there. No hooks, no filters. You're out of luck for tapping into that cleanly. Luckily you can do a duct tape method to still add it with jQuery. You can dynamically put text where you've circled by doing something like: ``` add_action( 'admin_head', function(){ global $wp_query; $screen = get_current_screen(); if ($screen->base == 'edit-tags' || $screen->base == 'term') { $mytax = get_taxonomy($screen->taxonomy); if (!empty($mytax->description)) { ?> <script> jQuery(window).load(function() { jQuery('.wrap h1').after("<p class='description'><?php echo $mytax->description ?></p>"); }); </script> <?php } } }); ``` --- UPDATE ------ As you pointed out @Slam, you can use the `_pre_add_form` and `_term_edit_form_top` hooks to show the into around the area you're after. To do that, you can cycle through all the taxonomies and dynamically run the actions like so: ``` add_action( 'admin_init', function(){ $taxonomies = get_taxonomies(); foreach ( $taxonomies as $taxonomy ) { add_action("{$taxonomy}_pre_add_form", 'my_plugin_tax_description'); add_action("{$taxonomy}_term_edit_form_top", 'my_plugin_tax_description'); } }); function my_plugin_tax_description() { global $wp_query; $screen = get_current_screen(); if ($screen->base == 'edit-tags' || $screen->base == 'term') { $mytax = get_taxonomy($screen->taxonomy); if (!empty($mytax->description)) echo "<p class='description'>{$mytax->description}</p>"; } } ``` Although `_pre_add_form` fires in the left column - not directly below the h1 title.
289,979
<p>I have a problem with my wordpress site logo. I cannot make the site logo dynamic. </p> <p>here is my code (displaying logo) which is in header.php page: </p> <pre><code>&lt;a href="&lt;?php echo get_home_url(); ?&gt;" id="logo"&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/assets/images/logo.png" class="img-responsive" alt="" title=""&gt; &lt;/a&gt; </code></pre> <p>***** when I want to change it from Customize > Site Identity, here it shows that no logo is attached, yet the logo is displaying successfully at front-end. Even when I try to change it, nothing happens.</p> <p>Kindly help me to solve this issue. </p>
[ { "answer_id": 289980, "author": "Tarang koradiya", "author_id": 128666, "author_profile": "https://wordpress.stackexchange.com/users/128666", "pm_score": 2, "selected": true, "text": "<p>Theme header logo function <code>get_theme_mod( 'custom_logo' );</code></p>\n\n<pre><code>$custom_lo...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/289979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132874/" ]
I have a problem with my wordpress site logo. I cannot make the site logo dynamic. here is my code (displaying logo) which is in header.php page: ``` <a href="<?php echo get_home_url(); ?>" id="logo"> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/logo.png" class="img-responsive" alt="" title=""> </a> ``` \*\*\*\*\* when I want to change it from Customize > Site Identity, here it shows that no logo is attached, yet the logo is displaying successfully at front-end. Even when I try to change it, nothing happens. Kindly help me to solve this issue.
Theme header logo function `get_theme_mod( 'custom_logo' );` ``` $custom_logo_id = get_theme_mod( 'custom_logo' ); $image = wp_get_attachment_image_src( $custom_logo_id , 'full' ); echo '<img class="header_logo" src="'.$image[0].'">'; ```
289,997
<p>I have the following in my database</p> <pre><code>siteurl subdomain.example.com home subdomain.example.com </code></pre> <p>and when I attempt to go to some pages, the pages go to <code>subdomain.example.com/services/subdomain.example.com</code></p> <p>Is there any reason why this would happen? I can't get into the wp-admin either because of this weird error and I can't understand why it would be happening?</p> <p>I've attempted to change the values in the database with <code>http://</code> prepended already also.</p> <p>Any advice is appreciated.</p>
[ { "answer_id": 289980, "author": "Tarang koradiya", "author_id": 128666, "author_profile": "https://wordpress.stackexchange.com/users/128666", "pm_score": 2, "selected": true, "text": "<p>Theme header logo function <code>get_theme_mod( 'custom_logo' );</code></p>\n\n<pre><code>$custom_lo...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/289997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134191/" ]
I have the following in my database ``` siteurl subdomain.example.com home subdomain.example.com ``` and when I attempt to go to some pages, the pages go to `subdomain.example.com/services/subdomain.example.com` Is there any reason why this would happen? I can't get into the wp-admin either because of this weird error and I can't understand why it would be happening? I've attempted to change the values in the database with `http://` prepended already also. Any advice is appreciated.
Theme header logo function `get_theme_mod( 'custom_logo' );` ``` $custom_logo_id = get_theme_mod( 'custom_logo' ); $image = wp_get_attachment_image_src( $custom_logo_id , 'full' ); echo '<img class="header_logo" src="'.$image[0].'">'; ```
289,999
<p>How can i change the recent post widget title programmatically?</p> <p>I use this code in my footer.php to add recent posts widget.</p> <pre><code>&lt;?php the_widget( 'WP_Widget_Recent_Posts' ); ?&gt; </code></pre>
[ { "answer_id": 290002, "author": "Mostafa Norzade", "author_id": 131388, "author_profile": "https://wordpress.stackexchange.com/users/131388", "pm_score": 1, "selected": false, "text": "<p>One of the ways is:</p>\n\n<p>1) Rename the Widget class name</p>\n\n<p>2) Modify the Widget class<...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/289999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132099/" ]
How can i change the recent post widget title programmatically? I use this code in my footer.php to add recent posts widget. ``` <?php the_widget( 'WP_Widget_Recent_Posts' ); ?> ```
I had a similar situation. Add the following code to your functions.php and see if it works for you. ``` function my_widget_title($title, $instance, $id_base) { if ( 'recent-posts' == $id_base) { return __('New Title'); } else { return $title; } } add_filter ( 'widget_title' , 'my_widget_title', 10, 3); ``` > > Note: this will change the title of all the "Recent Post" widgets. > > >
290,005
<p>I would like to generate a simple text report for a Wordpress instance listing:</p> <ul> <li>Wordpress version</li> <li>plugins installed (version and whether enabled)</li> <li>themes and child themes installed (version and whether enabled)</li> </ul> <p>I can get this information from the Dashboard, but is there a way to get it programmatically (with WP CLI, WP API or regular command line calls)?</p>
[ { "answer_id": 290020, "author": "lofidevops", "author_id": 31388, "author_profile": "https://wordpress.stackexchange.com/users/31388", "pm_score": 2, "selected": false, "text": "<p>Using WP CLI, you can record Wordpress version using:</p>\n\n<pre><code>wp core version --extra --path=\"$...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31388/" ]
I would like to generate a simple text report for a Wordpress instance listing: * Wordpress version * plugins installed (version and whether enabled) * themes and child themes installed (version and whether enabled) I can get this information from the Dashboard, but is there a way to get it programmatically (with WP CLI, WP API or regular command line calls)?
Using WP CLI, you can record Wordpress version using: ``` wp core version --extra --path="$SITEPATH" > wp-report.txt ``` and append a list of plugins (with status and version): ``` wp plugin list --path="$SITEPATH" >> wp-report.txt ``` and append a list of themes (with status and version) using: ``` wp theme list --path="$SITEPATH" >> wp-report.txt ``` **Further reading:** * <https://developer.wordpress.org/cli/commands/core/version/> * <https://developer.wordpress.org/cli/commands/plugin/list/> * <https://developer.wordpress.org/cli/commands/theme/list/>
290,015
<p>I am developing a free theme and users can download it from WordPress.org. I am working on pro version of the same theme. What should be the name of the pro version's folder? </p> <p>My theme's name is BizPoint. If I name the pro version's folder as 'BizPoint-Pro', whatever changes the user has done using customizer, are lost. If I use pro version's folder name as 'BizPoint', users won't be able to install pro version without deleting the free theme.</p> <p>How is this conflict handled?</p>
[ { "answer_id": 290020, "author": "lofidevops", "author_id": 31388, "author_profile": "https://wordpress.stackexchange.com/users/31388", "pm_score": 2, "selected": false, "text": "<p>Using WP CLI, you can record Wordpress version using:</p>\n\n<pre><code>wp core version --extra --path=\"$...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128132/" ]
I am developing a free theme and users can download it from WordPress.org. I am working on pro version of the same theme. What should be the name of the pro version's folder? My theme's name is BizPoint. If I name the pro version's folder as 'BizPoint-Pro', whatever changes the user has done using customizer, are lost. If I use pro version's folder name as 'BizPoint', users won't be able to install pro version without deleting the free theme. How is this conflict handled?
Using WP CLI, you can record Wordpress version using: ``` wp core version --extra --path="$SITEPATH" > wp-report.txt ``` and append a list of plugins (with status and version): ``` wp plugin list --path="$SITEPATH" >> wp-report.txt ``` and append a list of themes (with status and version) using: ``` wp theme list --path="$SITEPATH" >> wp-report.txt ``` **Further reading:** * <https://developer.wordpress.org/cli/commands/core/version/> * <https://developer.wordpress.org/cli/commands/plugin/list/> * <https://developer.wordpress.org/cli/commands/theme/list/>
290,018
<p>I am testing plugin upgrades on a staging instance before applying them to production. But if there are any delays in this process, I may end up being prompted to upgrade to a newer, untested version on production.</p> <p>If prompted to upgrade a plugin, how can I choose an intermediary update, rather than the latest?</p>
[ { "answer_id": 290019, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 6, "selected": true, "text": "<p>Using WP-CLI you can specify this as described in the <a href=\"https://developer.wordpress.org/cli/commands/pl...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290018", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31388/" ]
I am testing plugin upgrades on a staging instance before applying them to production. But if there are any delays in this process, I may end up being prompted to upgrade to a newer, untested version on production. If prompted to upgrade a plugin, how can I choose an intermediary update, rather than the latest?
Using WP-CLI you can specify this as described in the [official documentation](https://developer.wordpress.org/cli/commands/plugin/update/). ``` $ wp plugin update <plugin> ``` Using either of the following arguments ``` --minor ``` > > Only perform updates for minor releases (e.g. from 1.3 to 1.4 instead of 2.0) > > > ``` --patch ``` > > Only perform updates for patch releases (e.g. from 1.3 to 1.3.3 instead of 1.4) > > > ``` --version=<version> ``` > > If set, the plugin will be updated to the specified version. > > >
290,022
<p>I'm trying to configure the WordPress cookie expiration time, but for some reason it's not working. I went here:</p> <p><a href="https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/</a></p> <p>And put the following hook based on the doc:</p> <pre><code>function init() { // ... $expiration = 60; apply_filters( 'auth_cookie_expiration', $expiration ); } </code></pre> <p>This code is called from a hook in my plugin's constructor:</p> <pre><code>add_action( 'init', array( $this, 'init' ) ); </code></pre> <p>And I have verified that it runs.</p> <p>I expected this to produce a cookie that expires in 60 seconds, but it doesn't. Instead it sets a regular expiration time of 48 hours (WP default). I suspect this might be because when the user actually logs in, it doesn't create this expiration date, and running this function later has no effect. I haven't yet figured out how to make it work though. Any help appreciated.</p>
[ { "answer_id": 290024, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>Note that you're not adding any filter callback with:</p>\n\n<pre><code>apply_filters( 'auth_cookie_expiration...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33019/" ]
I'm trying to configure the WordPress cookie expiration time, but for some reason it's not working. I went here: <https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/> And put the following hook based on the doc: ``` function init() { // ... $expiration = 60; apply_filters( 'auth_cookie_expiration', $expiration ); } ``` This code is called from a hook in my plugin's constructor: ``` add_action( 'init', array( $this, 'init' ) ); ``` And I have verified that it runs. I expected this to produce a cookie that expires in 60 seconds, but it doesn't. Instead it sets a regular expiration time of 48 hours (WP default). I suspect this might be because when the user actually logs in, it doesn't create this expiration date, and running this function later has no effect. I haven't yet figured out how to make it work though. Any help appreciated.
Note that you're not adding any filter callback with: ``` apply_filters( 'auth_cookie_expiration', $expiration ); ``` Instead use: ``` add_filter( 'auth_cookie_expiration', $callback, 10, 3 ); ``` where `$callback` is the appropriate filter callback that modifies the expiration. Here's an example ``` add_filter( 'auth_cookie_expiration', function( $length, $user_id, $remember ) { return $length; // adjust this to your needs. }, 10, 3 ); ``` or to fit with your current class setup: ``` add_filter( 'auth_cookie_expiration', [ $this, 'set_auth_cookie_expiration' ], 10, 3 ); ``` where `set_auth_cookie_expiration()` is the appropriate method, e.g.: ``` public function set_auth_cookie_expiration ( $length, $user_id, $remember ) { return $length; // adjust this to your needs. } ```
290,030
<p>I have an <code>add_filter</code> function for the <code>auth_cookie_expiration</code> hook. This hook accepts three parameters. However, I am interested in passing it more parameters. For example:</p> <pre><code>add_filter( 'auth_cookie_expiration', 'get_expiration', 10, 5 ); </code></pre> <p>This would be possible with <code>apply_filter</code>, but the <code>add_filter</code> function is called once, which makes it throw an error:</p> <pre><code>PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function get_expiration(), 3 passed in ... and exactly 5 expected </code></pre> <p>I got around this using closures, but it seems like a completely ridiculous way to do this:</p> <pre><code>add_filter( 'auth_cookie_expiration', function() use ($param1, $param2) { return get_expiration(null, null, null, $param1, $param2); } , 10, 3 ); </code></pre> <p>Is there a proper/more elegant way to make it accept additional parameters (even better, the params I want in place of the default ones)? Am I misunderstanding how <code>add_filter</code> is supposed to work?</p> <p>For the sake of example, suppose <code>get_expiration</code> looks like this:</p> <pre><code>function get_expiration( $length, $user_id, $remember, $param1, $param2 ) { return $param1 + $param2; } </code></pre>
[ { "answer_id": 290076, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Am I misunderstanding how add_filter is supposed to work?</p>\n</blockquote>\n...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290030", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33019/" ]
I have an `add_filter` function for the `auth_cookie_expiration` hook. This hook accepts three parameters. However, I am interested in passing it more parameters. For example: ``` add_filter( 'auth_cookie_expiration', 'get_expiration', 10, 5 ); ``` This would be possible with `apply_filter`, but the `add_filter` function is called once, which makes it throw an error: ``` PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function get_expiration(), 3 passed in ... and exactly 5 expected ``` I got around this using closures, but it seems like a completely ridiculous way to do this: ``` add_filter( 'auth_cookie_expiration', function() use ($param1, $param2) { return get_expiration(null, null, null, $param1, $param2); } , 10, 3 ); ``` Is there a proper/more elegant way to make it accept additional parameters (even better, the params I want in place of the default ones)? Am I misunderstanding how `add_filter` is supposed to work? For the sake of example, suppose `get_expiration` looks like this: ``` function get_expiration( $length, $user_id, $remember, $param1, $param2 ) { return $param1 + $param2; } ```
The second parameter in `add_filter` is a function with **accepted arguments**, not returned values. This is an example how I pass my custom array `$args` to change an existing array `$filter_args`: ``` add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) { return eswc_var_dropdown_args( $filter_args, $args ); } ); function eswc_var_dropdown_args( $filter_args, $args ) { $filter_args['show_option_none'] = $args['var_select_text']; return $filter_args; } ```
290,036
<p>I don't know why the SHOW ALL is not displaying. It needs to display when the there are more than 6 posts under BOOKS. </p> <pre><code>&lt;?php for($k=0;$k&lt;count($results);$k++){ $ID = $results[$k]['book_id']; $args = array('p' =&gt; $ID, 'post_type' =&gt; 'attraction'); $loop = new WP_Query($args); $book_img = get_the_post_thumbnail( $ID, 'medium', array( 'class' =&gt; 'alignleft' ) ); if ($book_img) { //NOTHING TO SHOW } } ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'book', 'showposts'=&gt; 6, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'destinations', 'terms' =&gt; $current_term-&gt;term_id, ) ) ); $books = new WP_Query($args); echo '&lt;ul class="discover-books country-details"&gt;'; if ( $books-&gt;have_posts() ) { while ( $books-&gt;have_posts() ) : $books-&gt;the_post(); $book_img = get_the_post_thumbnail( get_the_ID(), 'medium', array( 'class' =&gt; 'alignleft' ) ); echo '&lt;li class="discover-single-box"&gt;&lt;span class="discover-cell imageFit dimensions_img"&gt;&lt;a href="'.get_permalink().'"&gt;'.$book_img.'&lt;/a&gt;&lt;span class="bottom-content"&gt;&lt;a href="'.get_permalink().'"&gt;'.get_the_title().'&lt;/a&gt;&lt;/span&gt; &lt;/span&gt;&lt;/li&gt;'; endwhile; } echo '&lt;/ul&gt;'; if(count($results) &gt; 6) { echo '&lt;div class="show-more"&gt;&lt;a href="'.get_site_url().'/book?id='.base64_encode($current_term-&gt;term_id).'"&gt;SHOW ALL&lt;/a&gt;&lt;/div&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 290076, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Am I misunderstanding how add_filter is supposed to work?</p>\n</blockquote>\n...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134208/" ]
I don't know why the SHOW ALL is not displaying. It needs to display when the there are more than 6 posts under BOOKS. ``` <?php for($k=0;$k<count($results);$k++){ $ID = $results[$k]['book_id']; $args = array('p' => $ID, 'post_type' => 'attraction'); $loop = new WP_Query($args); $book_img = get_the_post_thumbnail( $ID, 'medium', array( 'class' => 'alignleft' ) ); if ($book_img) { //NOTHING TO SHOW } } ?> <?php $args = array( 'post_type' => 'book', 'showposts'=> 6, 'tax_query' => array( array( 'taxonomy' => 'destinations', 'terms' => $current_term->term_id, ) ) ); $books = new WP_Query($args); echo '<ul class="discover-books country-details">'; if ( $books->have_posts() ) { while ( $books->have_posts() ) : $books->the_post(); $book_img = get_the_post_thumbnail( get_the_ID(), 'medium', array( 'class' => 'alignleft' ) ); echo '<li class="discover-single-box"><span class="discover-cell imageFit dimensions_img"><a href="'.get_permalink().'">'.$book_img.'</a><span class="bottom-content"><a href="'.get_permalink().'">'.get_the_title().'</a></span> </span></li>'; endwhile; } echo '</ul>'; if(count($results) > 6) { echo '<div class="show-more"><a href="'.get_site_url().'/book?id='.base64_encode($current_term->term_id).'">SHOW ALL</a></div>'; } ?> ```
The second parameter in `add_filter` is a function with **accepted arguments**, not returned values. This is an example how I pass my custom array `$args` to change an existing array `$filter_args`: ``` add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) { return eswc_var_dropdown_args( $filter_args, $args ); } ); function eswc_var_dropdown_args( $filter_args, $args ) { $filter_args['show_option_none'] = $args['var_select_text']; return $filter_args; } ```
290,037
<pre><code>&lt;img src="&lt;?php echo get_bloginfo('template_url') ?&gt;/images/logo.png"/&gt; </code></pre> <p>Is the above still a relevant method of embedding images in the Wordpress theme or an obsolete?</p> <p>If obsolete then what will be the correct method?</p> <p>someone questioned me today that I am not doing it correctly?</p>
[ { "answer_id": 290076, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Am I misunderstanding how add_filter is supposed to work?</p>\n</blockquote>\n...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290037", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` <img src="<?php echo get_bloginfo('template_url') ?>/images/logo.png"/> ``` Is the above still a relevant method of embedding images in the Wordpress theme or an obsolete? If obsolete then what will be the correct method? someone questioned me today that I am not doing it correctly?
The second parameter in `add_filter` is a function with **accepted arguments**, not returned values. This is an example how I pass my custom array `$args` to change an existing array `$filter_args`: ``` add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) { return eswc_var_dropdown_args( $filter_args, $args ); } ); function eswc_var_dropdown_args( $filter_args, $args ) { $filter_args['show_option_none'] = $args['var_select_text']; return $filter_args; } ```
290,075
<p>Is there a way to bold a specific word or part of a widget title? For example the title "Foo Bar", "Foo" here would be bold.</p> <p>I tried doing the following, but the span gets outputted in the title:</p> <pre><code>add_filter( 'widget_title', 'test', 10, 1); function test( $content ) { $test = explode(' ', $content); if ( !empty($test[1] ) ) { $title = '&lt;span class="this_is_bold"&gt;' . $test[0] . '&lt;/span&gt;'; $title = $title . ' ' . $test[1]; } return $title; } </code></pre>
[ { "answer_id": 290079, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p>This bolds the first words (or entire word, if only one) of my widget titles:</p>\n\n<pre><code>add_fil...
2018/01/03
[ "https://wordpress.stackexchange.com/questions/290075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90300/" ]
Is there a way to bold a specific word or part of a widget title? For example the title "Foo Bar", "Foo" here would be bold. I tried doing the following, but the span gets outputted in the title: ``` add_filter( 'widget_title', 'test', 10, 1); function test( $content ) { $test = explode(' ', $content); if ( !empty($test[1] ) ) { $title = '<span class="this_is_bold">' . $test[0] . '</span>'; $title = $title . ' ' . $test[1]; } return $title; } ```
This bolds the first words (or entire word, if only one) of my widget titles: ``` add_filter( 'widget_title', function ( $title ) { return preg_replace("/^(.+?)( |$)/", "<strong>$0</strong>", $title, 1); }, 10, 1); ``` Breaking down the regex pattern, we have: * `^` is the start of the line * `(.+?)` is anything between our next group (in this context, a word) * `( |$)` means either the first space, or the end of the line + the first space would be a normal title with multiple words + the end of line would mean a space wasn't found, so the title is just one word In `preg_replace()`, we have a fourth attribute set to `1`, it's the limit. This means the replace will only work on the first instance (which doesn't matter much in this context, as we know `$title` is always a single line so because of our start of line anchor `^` we know it can only work once always - but hey, why not). Please keep in mind I put the code in an anonymous function for minimal code (showing off). If this is for a plugin or a public theme, best to stick to doing the function call as you originally did.
290,090
<p>I have created a custom post type called Course Documents using WordPress <a href="https://wordpress.org/plugins/custom-post-type-ui/" rel="nofollow noreferrer">Custom Post Type UI</a> plugin. Also, I have created a new user role called Teacher.</p> <pre><code>add_role('rpt_teacher', 'Teacher', array( 'read' =&gt; true, 'edit_posts' =&gt; false, 'delete_posts' =&gt; false, 'publish_posts' =&gt; false, 'upload_files' =&gt; true, ) ); </code></pre> <p>And now I want to enable the custom post type in teacher dashboard nav menu. I have used below code in my functions.php but nothing happens. How can I resolve my issue?</p> <pre><code>add_action('admin_init','rpt_add_role_caps',999); /** add teachers capability */ function rpt_add_role_caps() { // Add the roles you'd like to administer the custom post types $roles = array('rpt_teacher','editor','administrator'); // Loop through each role and assign capabilities foreach($roles as $the_role) { $role = get_role($the_role); $role-&gt;add_cap( 'read' ); $role-&gt;add_cap( 'read_course_document'); $role-&gt;add_cap( 'edit_course_document' ); $role-&gt;add_cap( 'edit_course_documents' ); $role-&gt;add_cap( 'edit_published_course_documents' ); $role-&gt;add_cap( 'publish_course_documents' ); $role-&gt;add_cap( 'delete_published_course_documents' ); } } </code></pre>
[ { "answer_id": 290093, "author": "Sid", "author_id": 110516, "author_profile": "https://wordpress.stackexchange.com/users/110516", "pm_score": 1, "selected": false, "text": "<p>The way I see it, you are on the right track. You created a user and assign new capabilities to it. You just mi...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66897/" ]
I have created a custom post type called Course Documents using WordPress [Custom Post Type UI](https://wordpress.org/plugins/custom-post-type-ui/) plugin. Also, I have created a new user role called Teacher. ``` add_role('rpt_teacher', 'Teacher', array( 'read' => true, 'edit_posts' => false, 'delete_posts' => false, 'publish_posts' => false, 'upload_files' => true, ) ); ``` And now I want to enable the custom post type in teacher dashboard nav menu. I have used below code in my functions.php but nothing happens. How can I resolve my issue? ``` add_action('admin_init','rpt_add_role_caps',999); /** add teachers capability */ function rpt_add_role_caps() { // Add the roles you'd like to administer the custom post types $roles = array('rpt_teacher','editor','administrator'); // Loop through each role and assign capabilities foreach($roles as $the_role) { $role = get_role($the_role); $role->add_cap( 'read' ); $role->add_cap( 'read_course_document'); $role->add_cap( 'edit_course_document' ); $role->add_cap( 'edit_course_documents' ); $role->add_cap( 'edit_published_course_documents' ); $role->add_cap( 'publish_course_documents' ); $role->add_cap( 'delete_published_course_documents' ); } } ```
I don't think the plugin adds the capabilities you are using in `add_cap` while registering the post type. You can modify the registered post type by adding code to themes `functions.php` file. You can do something like this. ``` /** * Overwrite args of custom post type registered by plugin */ add_filter( 'register_post_type_args', 'change_capabilities_of_course_document' , 10, 2 ); function change_capabilities_of_course_document( $args, $post_type ){ // Do not filter any other post type if ( 'course_document' !== $post_type ) { // Give other post_types their original arguments return $args; } // Change the capabilities of the "course_document" post_type $args['capabilities'] = array( 'edit_post' => 'edit_course_document', 'edit_posts' => 'edit_course_documents', 'edit_others_posts' => 'edit_other_course_documents', 'publish_posts' => 'publish_course_documents', 'read_post' => 'read_course_document', 'read_private_posts' => 'read_private_course_documents', 'delete_post' => 'delete_course_document' ); // Give the course_document post type it's arguments return $args; } ``` Then you can do ``` /** add teachers capability */ add_action('admin_init','rpt_add_role_caps',999); function rpt_add_role_caps() { $role = get_role('teacher'); $role->add_cap( 'read_course_document'); $role->add_cap( 'edit_course_document' ); $role->add_cap( 'edit_course_documents' ); $role->add_cap( 'edit_other_course_documents' ); $role->add_cap( 'edit_published_course_documents' ); $role->add_cap( 'publish_course_documents' ); $role->add_cap( 'read_private_course_documents' ); $role->add_cap( 'delete_course_document' ); } ``` You don't need to add capability to administrator and editor because the `capability_type` is `post` by default while registering Custom Post Type via this plugin. You can change it, if you prefer to have custom `capability_type` based on other post type. Note: Make sure `Show in Menu` is set to `true`. It is `true` by default in this plugin.
290,118
<pre><code> wp_editor( $default_content, $editor_id,array('textarea_name' =&gt; $option_name,'media_buttons' =&gt; false,'editor_height' =&gt; 350,'teeny' =&gt; true) ); submit_button('Save', 'primary'); </code></pre> <p>I want to create a mail template where admin can change content and put shortcode where he wants. </p> <p>created a form and wrote the code above but when I click on save it not save the HTML formatted content.</p> <p>please help any one</p>
[ { "answer_id": 290329, "author": "result", "author_id": 134376, "author_profile": "https://wordpress.stackexchange.com/users/134376", "pm_score": -1, "selected": false, "text": "<p>Very simple</p>\n\n<p>if (isset($_POST[$editor_id])){\n update_option('name_option_you_want', $editor_id...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290118", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96956/" ]
``` wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) ); submit_button('Save', 'primary'); ``` I want to create a mail template where admin can change content and put shortcode where he wants. created a form and wrote the code above but when I click on save it not save the HTML formatted content. please help any one
``` echo '<form action="" class="booked-settings-form" method="post">'; $default_content='<p>Mail formate</p>'; $editor_id = 'customerCleanerMail'; $option_name='customerCleanerMail'; $default_content=html_entity_decode($default_content); $default_content=stripslashes($default_content); wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) ); submit_button('Save', 'primary'); echo '</form>'; if(isset($_POST['customerCleanerMail']) ){ $var2=htmlentities(wpautop($_POST['customerCleanerMail'])); $fff=update_option('customerCleanerMail', $var2); } ``` In form section i used wp\_editor with his options, wp\_editor work like html editor but when you store these data it not storing html data. so we found solution how to store html data wpautop() and htmlentities() both two functions help to store html formated data
290,120
<p>I have two custom fields, and both have numeric values:</p> <p>tnid_01</p> <p>tnid_01old</p> <p>Custom Field 'tnid_01' exists for all posts.</p> <p>Custom Field 'tnid_01old' only exists for some posts.</p> <p>I am trying to replace the value of 'tnid_01' with the value of 'tnid_01old', but only if 'tnid_01old' exists.</p> <p>This is what i have so far, but i get a mysql error:</p> <pre><code>Update wp_postmeta (post_id, meta_key, meta_value)( SELECT post_id, 'tnid_01', meta_value FROM wp_postmeta WHERE meta_key='tnid_01old' ); </code></pre> <p>thx</p>
[ { "answer_id": 290329, "author": "result", "author_id": 134376, "author_profile": "https://wordpress.stackexchange.com/users/134376", "pm_score": -1, "selected": false, "text": "<p>Very simple</p>\n\n<p>if (isset($_POST[$editor_id])){\n update_option('name_option_you_want', $editor_id...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110297/" ]
I have two custom fields, and both have numeric values: tnid\_01 tnid\_01old Custom Field 'tnid\_01' exists for all posts. Custom Field 'tnid\_01old' only exists for some posts. I am trying to replace the value of 'tnid\_01' with the value of 'tnid\_01old', but only if 'tnid\_01old' exists. This is what i have so far, but i get a mysql error: ``` Update wp_postmeta (post_id, meta_key, meta_value)( SELECT post_id, 'tnid_01', meta_value FROM wp_postmeta WHERE meta_key='tnid_01old' ); ``` thx
``` echo '<form action="" class="booked-settings-form" method="post">'; $default_content='<p>Mail formate</p>'; $editor_id = 'customerCleanerMail'; $option_name='customerCleanerMail'; $default_content=html_entity_decode($default_content); $default_content=stripslashes($default_content); wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) ); submit_button('Save', 'primary'); echo '</form>'; if(isset($_POST['customerCleanerMail']) ){ $var2=htmlentities(wpautop($_POST['customerCleanerMail'])); $fff=update_option('customerCleanerMail', $var2); } ``` In form section i used wp\_editor with his options, wp\_editor work like html editor but when you store these data it not storing html data. so we found solution how to store html data wpautop() and htmlentities() both two functions help to store html formated data
290,128
<p>The code in question →</p> <pre><code>&lt;?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?&gt; </code></pre> <p>The generated output in <strong>browser</strong> is like this → </p> <pre><code>&lt;img width="1620" height="973" src="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg 1620w, http://......./site04/wp-content/uploads/2018/01/audi_ileana-300x180.jpg 300w, ....../site04/wp-content/uploads/2018/01/audi_ileana-768x461.jpg 768w, http://....../site04/wp-content/uploads/2018/01/audi_ileana-1024x615.jpg 1024w" sizes="(max-width: 1620px) 100vw, 1620px"&gt; </code></pre> <h1>Anticipated result →</h1> <p>I want that height should output as "auto" value. </p> <hr> <p><strong>I tried this:</strong></p> <pre><code>&lt;div class="pimg"&gt; &lt;?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?&gt; &lt;/div&gt; </code></pre> <p>and its css:</p> <pre><code>.pimg img {max-with:100%; height:auto;} </code></pre>
[ { "answer_id": 290131, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": 3, "selected": true, "text": "<p>You can use a filter to remove height and width attributes from images, as explained in this <a href=\"https://...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
The code in question → ``` <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?> ``` The generated output in **browser** is like this → ``` <img width="1620" height="973" src="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg 1620w, http://......./site04/wp-content/uploads/2018/01/audi_ileana-300x180.jpg 300w, ....../site04/wp-content/uploads/2018/01/audi_ileana-768x461.jpg 768w, http://....../site04/wp-content/uploads/2018/01/audi_ileana-1024x615.jpg 1024w" sizes="(max-width: 1620px) 100vw, 1620px"> ``` Anticipated result → ==================== I want that height should output as "auto" value. --- **I tried this:** ``` <div class="pimg"> <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?> </div> ``` and its css: ``` .pimg img {max-with:100%; height:auto;} ```
You can use a filter to remove height and width attributes from images, as explained in this [CSS Tricks](https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/). Place the following in your themes `functions.php` file. ``` add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 ); add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 ); function remove_width_attribute( $html ) { $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); return $html; } ```
290,139
<p>I am using a hook from Paid Membership pro to add ACF fields on a registration form.</p> <pre><code>function insert_acf() { echo "&lt;p&gt;&lt;div id='content-creator'&gt;Test&lt;/div&gt;&lt;/p&gt; &lt;p&gt;&lt;?php the_field('organisation_name'); ?&gt;&lt;/p&gt;"; }; add_action('pmpro_checkout_before_submit_button','insert_acf'); </code></pre> <p>Problem 1: The test div works but it is not displaying the ACF field</p> <p>Problem 2: How do I associate this ACF field to the newly created subscriber</p> <p>TIA</p>
[ { "answer_id": 290131, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": 3, "selected": true, "text": "<p>You can use a filter to remove height and width attributes from images, as explained in this <a href=\"https://...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290139", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133457/" ]
I am using a hook from Paid Membership pro to add ACF fields on a registration form. ``` function insert_acf() { echo "<p><div id='content-creator'>Test</div></p> <p><?php the_field('organisation_name'); ?></p>"; }; add_action('pmpro_checkout_before_submit_button','insert_acf'); ``` Problem 1: The test div works but it is not displaying the ACF field Problem 2: How do I associate this ACF field to the newly created subscriber TIA
You can use a filter to remove height and width attributes from images, as explained in this [CSS Tricks](https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/). Place the following in your themes `functions.php` file. ``` add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 ); add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 ); function remove_width_attribute( $html ) { $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); return $html; } ```
290,143
<p>I wanted to add a new image size to the theme I have. But the image sizes are not working correctly.</p> <p>My code:</p> <pre><code>add_theme_support( 'post-thumbnails' ); add_image_size( 'bch-microsite-slider-image', 1450, 620 ); add_image_size( 'bch-microsite-hero-image', 1450, 315 ); add_image_size( 'bch-microsite-blog-image', 1000, 670, array( 'center', 'center') ); add_image_size( 'bch-microsite-blog-image1', 1000, 670 ); add_image_size( 'bch-microsite-blog-image2', 1000, 650 ); add_image_size( 'bch-microsite-blog-image3', 1000, 620 ); </code></pre> <p>The first two calls were already in the theme, but the apparently never worked right but I never really noticed since I wasn't using them. I added the 3rd call as what I wanted, and the 4th through 6th calls are an experiment. </p> <p>I used the plugin "Display All Image Sizes" to make sure I wasn't looking at things wrong, but in the Media Library, a newly uploaded image shows the following image sizes: <a href="https://i.stack.imgur.com/xqBoi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xqBoi.png" alt="enter image description here"></a></p> <p>The new sizes never exceed the "large" size, but I don't see a reference to that anywhere in the documentation. Do I have to change the "large" size, or is there some other problem? Any help would be greatly appreciated.</p> <p>Here are the results of running Regenerate Thumbnails are a single image: <a href="https://i.stack.imgur.com/sQtBV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sQtBV.png" alt="enter image description here"></a> All the image sizes reported by Regenerate Thumbnails are correct and it generates the correctly sized image files in the uploads folder. However, when selecting the image from the media library, the incorrect sizes are still being shown: <a href="https://i.stack.imgur.com/gAmVf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gAmVf.png" alt="enter image description here"></a></p> <p>When the 3rd size is inserted into a post the code uses the correctly sized file (artwork-1-1000x670.jpg) but uses the size reflected in the image size drop-down list (640 by 429).</p>
[ { "answer_id": 290131, "author": "Andrew", "author_id": 50767, "author_profile": "https://wordpress.stackexchange.com/users/50767", "pm_score": 3, "selected": true, "text": "<p>You can use a filter to remove height and width attributes from images, as explained in this <a href=\"https://...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290143", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78341/" ]
I wanted to add a new image size to the theme I have. But the image sizes are not working correctly. My code: ``` add_theme_support( 'post-thumbnails' ); add_image_size( 'bch-microsite-slider-image', 1450, 620 ); add_image_size( 'bch-microsite-hero-image', 1450, 315 ); add_image_size( 'bch-microsite-blog-image', 1000, 670, array( 'center', 'center') ); add_image_size( 'bch-microsite-blog-image1', 1000, 670 ); add_image_size( 'bch-microsite-blog-image2', 1000, 650 ); add_image_size( 'bch-microsite-blog-image3', 1000, 620 ); ``` The first two calls were already in the theme, but the apparently never worked right but I never really noticed since I wasn't using them. I added the 3rd call as what I wanted, and the 4th through 6th calls are an experiment. I used the plugin "Display All Image Sizes" to make sure I wasn't looking at things wrong, but in the Media Library, a newly uploaded image shows the following image sizes: [![enter image description here](https://i.stack.imgur.com/xqBoi.png)](https://i.stack.imgur.com/xqBoi.png) The new sizes never exceed the "large" size, but I don't see a reference to that anywhere in the documentation. Do I have to change the "large" size, or is there some other problem? Any help would be greatly appreciated. Here are the results of running Regenerate Thumbnails are a single image: [![enter image description here](https://i.stack.imgur.com/sQtBV.png)](https://i.stack.imgur.com/sQtBV.png) All the image sizes reported by Regenerate Thumbnails are correct and it generates the correctly sized image files in the uploads folder. However, when selecting the image from the media library, the incorrect sizes are still being shown: [![enter image description here](https://i.stack.imgur.com/gAmVf.png)](https://i.stack.imgur.com/gAmVf.png) When the 3rd size is inserted into a post the code uses the correctly sized file (artwork-1-1000x670.jpg) but uses the size reflected in the image size drop-down list (640 by 429).
You can use a filter to remove height and width attributes from images, as explained in this [CSS Tricks](https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/). Place the following in your themes `functions.php` file. ``` add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 ); add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 ); function remove_width_attribute( $html ) { $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); return $html; } ```
290,147
<p>I'm making a skin for The Grid plugin (<a href="https://theme-one.com/docs/the-grid/#developer_guide" rel="nofollow noreferrer">https://theme-one.com/docs/the-grid/#developer_guide</a>).</p> <p>All the products are virtual and downloadable — I've managed to make an add to cart function, but need to download products instantly too. Is there a meta key for the file url (combed the database and couldn't spot one) or a way to get it?</p> <p>Currently I've got something that just returns an array:</p> <pre><code>$output .= '&lt;p&gt;&lt;a href="' . $tg_el-&gt;get_item_meta('_downloadable_files') . '" download target="_blank"&gt;&lt;i class="fa fa-download"&gt;&lt;/i&gt; Download Image&lt;/a&gt;&lt;/p&gt;'; </code></pre> <p>Thought I'd found a possible solution: <a href="https://wordpress.stackexchange.com/a/199884/134263">https://wordpress.stackexchange.com/a/199884/134263</a> but am not great with php and I'm unsure how to implement it.</p> <p>Any pointers would be much appreciated!</p>
[ { "answer_id": 291312, "author": "Dannie Herdyawan", "author_id": 68053, "author_profile": "https://wordpress.stackexchange.com/users/68053", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php \n $downloads = $product-&gt;get_files...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290147", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134263/" ]
I'm making a skin for The Grid plugin (<https://theme-one.com/docs/the-grid/#developer_guide>). All the products are virtual and downloadable — I've managed to make an add to cart function, but need to download products instantly too. Is there a meta key for the file url (combed the database and couldn't spot one) or a way to get it? Currently I've got something that just returns an array: ``` $output .= '<p><a href="' . $tg_el->get_item_meta('_downloadable_files') . '" download target="_blank"><i class="fa fa-download"></i> Download Image</a></p>'; ``` Thought I'd found a possible solution: <https://wordpress.stackexchange.com/a/199884/134263> but am not great with php and I'm unsure how to implement it. Any pointers would be much appreciated!
``` <?php $downloads = $product->get_files(); foreach( $downloads as $key => $download ) { echo '<p class="download-link"><a href="' . esc_url( $download['file'] ) . '">' . $download['name'] . '</a></p>'; } ?> ``` Check this.. Worked for me.
290,175
<p>My theme has an option on its page builder called "show portfolio category filter buttons" which places filter buttons for portfolio categories. As you can see from the following link, it fetches my portfolio categories, but when i push the buttons its not doing anyting. It was working before but it suddenly stopped working. Why do you think it's not working?</p> <p><a href="http://www.ekn.sinankarabulut.com/tum-urunler/dikey-enjeksiyonlar/" rel="nofollow noreferrer">http://www.ekn.sinankarabulut.com/tum-urunler/dikey-enjeksiyonlar/</a></p> <p>Thanks...</p>
[ { "answer_id": 290186, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 1, "selected": false, "text": "<p>Looks like there maybe a problem with your <code>plugins.js</code> on line 35 according to my console. I'm gett...
2018/01/04
[ "https://wordpress.stackexchange.com/questions/290175", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130811/" ]
My theme has an option on its page builder called "show portfolio category filter buttons" which places filter buttons for portfolio categories. As you can see from the following link, it fetches my portfolio categories, but when i push the buttons its not doing anyting. It was working before but it suddenly stopped working. Why do you think it's not working? <http://www.ekn.sinankarabulut.com/tum-urunler/dikey-enjeksiyonlar/> Thanks...
Looks like there maybe a problem with your `plugins.js` on line 35 according to my console. I'm getting the error `TypeError: portfolioContainer.imagesLoaded is not a function.` The code in question is: ``` if (jQuery().isotope){ var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h'); if (portfolioContainer) { portfolioContainer.imagesLoaded(function(){ portfolioContainer.isotope({ itemSelector : '.w-portfolio-item', layoutMode : 'fitRows' }); }); jQuery('.w-filters-item').each(function() { var item = jQuery(this), link = item.find('.w-filters-item-link'); link.click(function(){ if ( ! item.hasClass('active')) { jQuery('.w-filters-item').removeClass('active'); item.addClass('active'); var selector = jQuery(this).attr('data-filter'); portfolioContainer.isotope({ filter: selector }); return false; } }); }); jQuery('.w-portfolio-item-meta-tags a').each(function() { jQuery(this).click(function(){ var selector = jQuery(this).attr('data-filter'), topFilterLink = jQuery('a[class="w-filters-item-link"][data-filter="'+selector+'"]'), topFilter = topFilterLink.parent('.w-filters-item'); if ( ! topFilter.hasClass('active')) { jQuery('.w-filters-item').removeClass('active'); topFilter.addClass('active'); portfolioContainer.isotope({ filter: selector }); return false; } }); }); } ``` So it looks like it's an issue with the [Isotope.js](https://isotope.metafizzy.co/) library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available. Since it is a premium theme, you might want to check with the place you got it from and look into support.